﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web;

namespace Cotrobaie.WebServicies
{
    /// <summary>
    /// Summary description for Register
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class Users : System.Web.Services.WebService
    {
        private void InitializeComponent()
        {
            
        }
        #region Non-public
        private void MonitorHackers()
        {
            string IP = String.Empty;
            try { IP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; }
            catch { return; }
            using (var dbs = new DB.DBCotrobaie())
            {
                var usr = from v in dbs.IpuriBanate where v.IP.StartsWith(IP) && v.IP.Length == IP.Length select v;
                if (usr.Count<DB.IpuriBanate>() == 1)
                {
                    var user = usr.First<DB.IpuriBanate>();
                    if (user.Data <= DateTime.Now.AddDays(-1))
                    { user.Data = DateTime.Now; user.NrFailed = 1; }
                    else { user.NrFailed++; }
                }
                else
                {
                    dbs.AddToIpuriBanate(new DB.IpuriBanate() { IP = IP, NrFailed = 1, Data = DateTime.Now });
                }
                dbs.SaveChanges();
            }
        }
        private int UserIpuriBanate()
        {
            string IP = String.Empty;
            try { IP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; }
            catch { return 0; }
            using (var dbs = new DB.DBCotrobaie())
            {
                var usr = from v in dbs.IpuriBanate where v.IP.StartsWith(IP) && v.IP.Length == IP.Length select v;
                if (usr.Count<DB.IpuriBanate>() == 1)
                {
                    if (usr.First<DB.IpuriBanate>().Data < DateTime.Now.AddDays(-2))
                    {
                        usr.First<DB.IpuriBanate>().NrFailed = 0;
                        dbs.SaveChanges();
                        return 0;
                    }
                    return usr.First<DB.IpuriBanate>().NrFailed;
                }
                else return 0;
            }
        }
        #endregion

        #region Users

        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public Mesaje Register(string Username, string Parola, string Nume, string Prenume, string Email)
        {
            if (UserIpuriBanate() >= 20) return new Mesaje() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            string activCode = Misc.GenerateRandomCode(43);
            using (var dbs = new DB.DBCotrobaie())
            {
                if ((from u in dbs.Useri where u.Username.ToLower().Contains(Username.ToLower())&&u.Username.Length == Username.Length select u.ID).Count()>0)
                    return new Mesaje() { Success = false, Mesaj = "Ne pare rau dar " + Username + " este deja folosit" };
                if ((from u in dbs.Useri where u.E_mail.ToLower().Contains(Email.ToLower()) && u.E_mail.Length == Email.Length select u.ID).Count() > 0)
                    return new Mesaje() { Success = false, Mesaj = "Adresa de E-mail "+Email+" exista deja in baza noastra de date. Daca ati uitat numele de utilizator sau parola puteti accesa pagina de <a href='RecuperareParola.aspx'>recuperare a parolei</a>" };
                try
                {
                    dbs.AddToUseri(new DB.Useri() { Username = Username, Parola = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(Parola, "MD5"), Nume = Nume, Prenume = Prenume, E_mail = Email, DataInregistrare = DateTime.Now, DataUltimaLogare = DateTime.Now });
                    dbs.AddToEmailActivation(new DB.EmailActivation() { E_mail = Email, ActivationCode = activCode });
                    dbs.SaveChanges();
                }
                catch
                { return new Mesaje() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul inregistrarii. Va rugam mai incercati odata" }; }
            }
            if (SendEmail.SendVerificationEmail(Nume, Prenume, Email, activCode))
                return new Mesaje() { Success = true, Mesaj = Username + " a fost inregistrat cu succes. Un mail de confirmare a fost trimis catre adresa " + Email };
            else return new Mesaje() { Success = false, Mesaj = "A aparut o eroare in momentul trimiterii mail-ului catre adresa " + Email };
        }
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public Mesaje ActivareCont(string ActivationCode)
        {
            if (UserIpuriBanate() >= 20) return new Mesaje() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                var ac = from ea in dbs.EmailActivation where ea.ActivationCode.Contains(ActivationCode) select ea;
                if (ac.Count<DB.EmailActivation>()==0) return new Mesaje() { Success = false, Mesaj = "Codul de activare este incorect. Va rugam folositi codul din Email" };
                var v=ac.First<DB.EmailActivation>();
                
                Func<DB.Useri, bool> fct = (DB.Useri u) => u.E_mail == v.E_mail;
                var usri = from u in dbs.Useri where u.E_mail.Contains(v.E_mail) && u.E_mail.Length == v.E_mail.Length select u;
                if (usri.Count<DB.Useri>()==0) return new Mesaje() { Success = false, Mesaj = "Codul de activare este incorect. Va rugam folositi codul din Email" };
                var usr = usri.First<DB.Useri>();

                v.IsActivated = true;
                usr.AccountIsValidated = true;
                dbs.SaveChanges();
                return new Mesaje() { Success = true, Mesaj = "Contul a fost confirmat cu succes. Acum va puteti loga" };
            }
        }
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public MesajeUser Login(string UserUsername, string Password)
        {
            if (UserIpuriBanate() >= 20) return new MesajeUser() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                Password = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(Password, "MD5");
                var usri = (from u in dbs.Useri where u.Username.Contains(UserUsername) && u.Username.Length == UserUsername.Length && u.Parola.StartsWith(Password) && u.Parola.Length == Password.Length select u);
                if (usri.Count<DB.Useri>() == 1)
                {
                    var usr = usri.First<DB.Useri>();
                    if (!usr.AccountIsValidated) return new MesajeUser() { Success = false, Mesaj = "Contul nu a fost inca validat.<br/>Verificati-va casuta de e-mail" };
                    else if (usr.AccountIsSuspended) return new MesajeUser() { Success = false, Mesaj = "Contul dvs a fost suspendat.<br/>Pentru a remedia situatia va rugam folositi sectiunea Contact" };
                    else if (usr.AccountIsTempDeleted) return new MesajeUser() { Success = false, Mesaj = String.Format("Contul dvs a fost sters in data de {0:dd.MM.yyyy}.<br/>Pentru a remedia situatia va rugam folositi sectiunea Contact", usr.AccountTempDelDate) };
                    else
                    {
                        usr.DataUltimaLogare = DateTime.Now;
                        dbs.SaveChanges();
                        return new MesajeUser() { Success = true, Mesaj = "Login reusit", User = new TipUser() { ID = usr.ID, Email = usr.E_mail, Nume = usr.Nume, Prenume = usr.Prenume, Parola = usr.Parola, Username = usr.Username } };
                    }
                }
                else
                {
                    MonitorHackers();
                    return new MesajeUser() { Success = false, Mesaj = "Username sau parola gresita", User=new TipUser() };
                }
            }
        }
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public Mesaje RecuperareParola(string Username, string Email)
        {
            if (UserIpuriBanate() >= 20) return new Mesaje() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                var usri = from u in dbs.Useri where (u.Username.ToLower().Contains(Username.ToLower()) && u.Username.Length == Username.Length) || (u.E_mail.ToLower().Contains(Email.ToLower()) && u.E_mail.Length == Email.Length) select u;
                if (usri.Count<DB.Useri>() > 0)
                {
                    var usr = usri.First<DB.Useri>();
                    if (!usr.AccountIsValidated) return new Mesaje() { Success = false, Mesaj = "Contul dvs nu a fost validat. Verificati casuta de Email" };
                    else if (usr.AccountIsSuspended) return new Mesaje() { Success = false, Mesaj = "Contul dvs a fost suspendat" };
                    else if (usr.AccountIsTempDeleted) return new Mesaje() { Success = false, Mesaj = String.Format("Contul dvs a fost sters in data de {0:dd.MM.yyyy}. Contactati administratorul.", usr.AccountTempDelDate) };
                    else
                    {
                        string activCode = (from ea in dbs.EmailActivation where ea.E_mail.ToLower().Contains(usr.E_mail.ToLower()) && ea.E_mail.Length == usr.E_mail.Length select ea).First<DB.EmailActivation>().ActivationCode;
                        if (SendEmail.SendRecuperareParolaEmail(usr.Username, usr.E_mail, System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(activCode, "SHA1")))
                            return new Mesaje() { Success = true, Mesaj = "Un Email de recuperare a parolei a fost trimis catre " + usr.E_mail };
                        else return new Mesaje() { Success = false, Mesaj = "A aparut o eroare in momentul trimiterii mail-ului catre adresa " + Email };
                    }
                }
                else
                {
                    MonitorHackers();
                    return new Mesaje() { Success = false, Mesaj = "Atat Username-ul, cat si Email-ul nu apar in baza noastra de date" };
                }
            }
        }
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public Mesaje RecuperareParolaIntrodNouaParola(string Username, string Email, string CodActivare, string Parola)
        {
            if (UserIpuriBanate() >= 20) return new Mesaje() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                var usri = from u in dbs.Useri where (u.Username.ToLower().Contains(Username.ToLower()) && u.Username.Length == Username.Length) || (u.E_mail.ToLower().Contains(Email.ToLower()) && u.E_mail.Length == Email.Length) select u;
                if (usri.Count<DB.Useri>() > 0)
                {
                    var usr = usri.First<DB.Useri>();
                    if (!usr.AccountIsValidated) return new Mesaje() { Success = false, Mesaj = "Contul dvs nu a fost validat. Verificati casuta de Email" };
                    else if (usr.AccountIsSuspended) return new Mesaje() { Success = false, Mesaj = "Contul dvs a fost suspendat" };
                    else if (usr.AccountIsTempDeleted) return new Mesaje() { Success = false, Mesaj = String.Format("Contul dvs a fost sters in data de {0:dd.MM.yyyy}. Contactati administratorul.", usr.AccountTempDelDate) };
                    else
                    {
                        var resultEmailActiv = from ea in dbs.EmailActivation where ea.E_mail.ToLower().Contains(usr.E_mail.ToLower()) && ea.E_mail.Length == usr.E_mail.Length select ea;
                        Func<DB.EmailActivation, bool> fct2 = (DB.EmailActivation ea) => System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(ea.ActivationCode, "SHA1") == CodActivare;
                        if (resultEmailActiv.Where<DB.EmailActivation>(fct2).Count<DB.EmailActivation>() == 1)
                        {
                            usr.Parola = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(Parola, "MD5");
                            dbs.SaveChanges();
                            return new Mesaje() { Success = true, Mesaj = "Parola modificata cu succes. Acum va puteti loga cu noua parola" };
                        }
                        else return new Mesaje() { Success = false, Mesaj = "Codul de recuperare a parolei este gresit. Va rugam accesati inca odata linkul primit prin Email" };
                    }
                }
                else
                {
                    MonitorHackers();
                    return new Mesaje() { Success = false, Mesaj = "Atat Username-ul, cat si Email-ul nu apar in baza noastra de date" };
                }
            }
        }
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public Mesaje SchimbaProfil(int UserID, string UserUsername, string Password, string Nume, string Prenume, string Email, string NouaParola)
        {
            if (UserIpuriBanate() >= 20) return new Mesaje() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var resultUser = (from u in dbs.Useri where u.ID == UserID && u.Username.Contains(UserUsername) && u.Username.Length == UserUsername.Length && u.Parola.StartsWith(Password) && u.Parola.Length == Password.Length select u);
                    if (resultUser.Count() == 1)
                    {
                        var user = resultUser.First<DB.Useri>();
                        user.Nume = Nume; user.Prenume = Prenume;
                        user.E_mail = Email;
                        if (NouaParola != String.Empty) user.Parola = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(NouaParola, "MD5");
                        dbs.SaveChanges();
                        return new Mesaje() { Success = true, Mesaj = "Modificari efectuate cu succes" };
                    }
                    else
                    {
                        MonitorHackers();
                        return new Mesaje() { Success = false, Mesaj = "Va rugam delogati-va si logati-va inca odata" };
                    }
                }
                catch
                { return new Mesaje() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul modificarii. Va rugam mai incercati odata" }; }
            }
        }
        #endregion

        #region Admin
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public Mesaje LoginAdmin(string Username, string Password)
        {
            if (UserIpuriBanate() >= 20) return new Mesaje() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                Password =System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(Password, "MD5");
                var usri = from u in dbs.Admini where u.Username.ToLower().Contains(Username.ToLower()) && u.Username.Length == Username.Length && u.Password.Contains(Password) && u.Password.Length == Password.Length select u;
                if (usri.Count<DB.Admini>() > 0)
                {
                    var usr = usri.First<DB.Admini>();
                    usr.DataUltimaLogare = DateTime.Now;
                    dbs.SaveChanges();
                    return new Mesaje() { Success = true, Mesaj = "Login reusit" };
                }
                else
                {
                    MonitorHackers();
                    return new Mesaje() { Success = false, Mesaj = "Username sau parola gresita. Va rugam mai incercati odata" };
                }
            }
        }
        #endregion

        #region Bookmarks
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]//am lasat si id si uername si parola
            //parola este cea din baza de date (hash cu md5 la parola initiala, care nu este vizibila in clar deloc), la care mai facem un hash md5
            //practic este parola de baza a userului, cu 2 hash-uri succesive de md5 (atentie pe alte medii de dezvoltare sa faceti un toUpper la md5-ul final
        public Mesaje AddBookmark(int UserID, string UserUsername, string Password, long ProductID)
        {
            if (UserIpuriBanate() >= 20) return new Mesaje() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var resultUser = (from u in dbs.Useri where u.ID == UserID && u.Username.Contains(UserUsername) && u.Username.Length == UserUsername.Length && u.Parola.StartsWith(Password) && u.Parola.Length == Password.Length select u.ID);
                    if (resultUser.Count() == 1)
                    {
                        var resultProduct = (from p in dbs.Product where p.ID == ProductID select p.ID);
                        if (resultProduct.Count() == 1)
                        {
                            var resultBookmark = from b in dbs.Bookmark where b.user_id == resultUser.FirstOrDefault() && b.product_id == resultProduct.FirstOrDefault() select b.ID;
                            if (resultBookmark.Count() == 0)
                            {
                                dbs.AddToBookmark(new DB.Bookmark() { user_id = UserID, product_id = ProductID });
                                dbs.SaveChanges();
                                return new Mesaje() { Success = true, Mesaj = "Bookmark a fost adaugata cu succes" };
                            }
                            else return new Mesaje() { Success = true, Mesaj = "Bookmark deja existent" };
                        }
                        else return new Mesaje() { Success = false, Mesaj = "Produsul nu (mai) exista in baza noastra de date" };
                    }
                    else
                    {
                        MonitorHackers();
                        return new Mesaje() { Success = false, Mesaj = "Va rugam delogati-va si logati-va inca odata" };
                    }
                }
                catch
                { return new Mesaje() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul adaugarii. Va rugam mai incercati odata" }; }
            }
        }
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public Mesaje RemoveUserBookmark(int UserID, string UserUsername, string Password, long ProductID)
        {
            if (UserIpuriBanate() >= 20) return new Mesaje() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var resultUser = (from u in dbs.Useri where u.ID == UserID && u.Username.Contains(UserUsername) && u.Username.Length == UserUsername.Length && u.Parola.StartsWith(Password) && u.Parola.Length == Password.Length select u.ID);
                    if (resultUser.Count() == 1)
                    {
                        var resultProduct = (from p in dbs.Product where p.ID == ProductID select p.ID);
                        if (resultProduct.Count() == 1)
                        {
                            var resultBookmark = from b in dbs.Bookmark where b.user_id == resultUser.FirstOrDefault() && b.product_id == resultProduct.FirstOrDefault() select b;
                            if (resultBookmark.Count() == 0)
                            {
                                return new Mesaje() { Success = false, Mesaj = "Bookmark-ul nu (mai) exista in baza noastra de date" };
                            }
                            else
                            {
                                dbs.Bookmark.DeleteObject(resultBookmark.FirstOrDefault<DB.Bookmark>());
                                dbs.SaveChanges();
                                return new Mesaje() { Success = true, Mesaj = "Bookmark-ul a fost sters" };
                            }
                        }
                        else return new Mesaje() { Success = false, Mesaj = "Produsul nu (mai) exista in baza noastra de date" };
                    }
                    else
                    {
                        MonitorHackers();
                        return new Mesaje() { Success = false, Mesaj = "Va rugam delogati-va si logati-va inca odata" };
                    }
                }
                catch
                { return new Mesaje() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul stergerii. Va rugam mai incercati odata" }; }
            }
        }
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public Mesaje GetUserBookmark(int UserID, string UserUsername, string Password, long ProductID)
        {
            if (UserIpuriBanate() >= 20) return new Mesaje() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var resultUser = (from u in dbs.Useri where u.ID == UserID && u.Username.Contains(UserUsername) && u.Username.Length == UserUsername.Length && u.Parola.StartsWith(Password) && u.Parola.Length == Password.Length select u.ID).Count();
                    if (resultUser == 1)
                    {
                        var resultProduct=(from p in dbs.Product where p.ID==ProductID select p.ID).Count();
                        if (resultProduct == 1)
                        {
                            var resultBookmark = (from b in dbs.Bookmark where b.product_id == ProductID && b.user_id == UserID select b.ID);

                            return new Mesaje() { Success = resultBookmark.Count() >= 1, Mesaj = "Bookmark " + (resultBookmark.Count() < 1 ? "in" : "") + "existent" };
                        }
                        else return new Mesaje() { Success = false, Mesaj = "Produsul nu (mai) exista in baza noastra de date" };
                    }
                    else
                    {
                        MonitorHackers();
                        return new Mesaje() { Success = false, Mesaj = "Va rugam delogati-va si logati-va inca odata" };
                    }
                }
                catch
                { return new Mesaje() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata" }; }

            }
        }
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public MesajeProduse GetUserBookmarks(int UserID, string UserUsername, string Password, int Pagina, int IntrariPePagina)
        {
            if (UserIpuriBanate() >= 20) return new MesajeProduse() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var resultUser = (from u in dbs.Useri where u.ID == UserID && u.Username.Contains(UserUsername) && u.Username.Length == UserUsername.Length && u.Parola.StartsWith(Password) && u.Parola.Length == Password.Length select u.ID).Count();
                    if (resultUser == 1)
                    {
                        var produse = (from b in dbs.Bookmark where b.user_id == UserID join p in dbs.Product on b.product_id equals p.ID orderby b.Product.name ascending select new TipProdus() { ID = p.ID, name = p.name, brand = p.brand, description = p.description, imageSwatch = p.imageSwatch, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, UPC = p.UPC, ISBN = p.ISBN, categ_id = p.categ_id, categ_name = p.Category.name, authors = p.authors, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, KeyWords = p.KeyWords, Price = p.CurrPrice, NrAccesari = p.NrAccesari })
                            .Skip<TipProdus>(Pagina * IntrariPePagina).Take<TipProdus>(IntrariPePagina).ToList<TipProdus>();

                        foreach (var p in produse)
                        {
                            var rating = from r in dbs.Rating where r.product_id == p.ID select r.value; p.Rating = rating.Count() > 0 ? (rating.Sum() * 1.0 / rating.Count()) : 0;

                            //FOARTE IMPORTANT, nu am voie sa trimit in xml caractere precum < sau > sau </b> etc....
                            if (p.description != null) p.description = Microsoft.Security.Application.Encoder.HtmlEncode(p.description);
                            else p.description = String.Empty;
                            if (p.authors != null) p.authors = Microsoft.Security.Application.Encoder.HtmlEncode(p.authors).Replace("&#14;", " and ");
                            else p.authors = String.Empty;
                            p.linkSite = String.Concat("http://cotrobaie.cjb.net//product.aspx?ProductID=", p.ID.ToString());
                        }
                        return new MesajeProduse() { Success = true, Mesaj = produse.Count().ToString() + " bookmarks", Produse = produse };
                    }
                    else
                    {
                        MonitorHackers();
                        return new MesajeProduse() { Success = false, Mesaj = "Va rugam delogati-va si logati-va inca odata", Produse = new List<TipProdus>() };
                    }
                }
                catch
                { return new MesajeProduse() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata", Produse = new List<TipProdus>() }; }

            }
        }
        #endregion

        #region Alarm
        
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public Mesaje AddAlarmPrice(int UserID, string UserUsername, string Password, long ProductID, double AlertPrice)
        {
            if (UserIpuriBanate() >= 20) return new Mesaje() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var resultUser = (from u in dbs.Useri where u.ID == UserID && u.Username.Contains(UserUsername) && u.Username.Length == UserUsername.Length && u.Parola.StartsWith(Password) && u.Parola.Length == Password.Length select u.ID);
                    if (resultUser.Count() == 1)
                    {
                        var resultProduct = (from p in dbs.Product where p.ID == ProductID select p);
                        if (resultProduct.Count<DB.Product>() == 1)
                        {
                            var resultAlarm = from b in dbs.Subscribe where b.user_id == resultUser.FirstOrDefault() && b.product_id == resultProduct.FirstOrDefault().ID select b;
                            var pret = from p in dbs.Price where resultProduct.FirstOrDefault<DB.Product>().ID == p.product_id orderby p.timestamp descending select p;
                            if (resultAlarm.Count() == 0)
                            {
                                dbs.AddToSubscribe(new DB.Subscribe() { user_id = UserID, product_id = ProductID, price = pret.First<DB.Price>().price1 == null ? 0 : (double)pret.First<DB.Price>().price1, alertPrice = (AlertPrice != -1 ? AlertPrice : (double?)null) });
                                dbs.SaveChanges();
                                return new Mesaje() { Success = true, Mesaj = "Alarma a fost adaugata cu succes" };
                            }
                            else
                            {
                                var alarm = resultAlarm.First<DB.Subscribe>(); alarm.alertPrice = (AlertPrice != -1 ? AlertPrice : (double?)null); alarm.price = pret.First<DB.Price>().price1 == null ? 0 : (double)pret.First<DB.Price>().price1;
                                dbs.SaveChanges();
                                return new Mesaje() { Success = true, Mesaj = "Alarma a fost modificata cu succes" };
                            }
                        }
                        else return new Mesaje() { Success = false, Mesaj = "Produsul nu (mai) exista in baza noastra de date" };
                    }
                    else
                    {
                        MonitorHackers(); 
                        return new Mesaje() { Success = false, Mesaj = "Va rugam delogati-va si logati-va inca odata" };
                    }
                }
                catch
                { return new Mesaje() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul adaugarii. Va rugam mai incercati odata" }; }
            }
        }

        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public Mesaje AddAlarmProcent(int UserID, string UserUsername, string Password, long ProductID, double Percent)
        {
            if (UserIpuriBanate() >= 20) return new Mesaje() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var resultUser = (from u in dbs.Useri where u.ID == UserID && u.Username.Contains(UserUsername) && u.Username.Length == UserUsername.Length && u.Parola.StartsWith(Password) && u.Parola.Length == Password.Length select u.ID);
                    if (resultUser.Count() == 1)
                    {
                        var resultProduct = (from p in dbs.Product where p.ID == ProductID select p);
                        if (resultProduct.Count<DB.Product>() == 1)
                        {
                            var resultAlarm = from b in dbs.Subscribe where b.user_id == resultUser.FirstOrDefault() && b.product_id == resultProduct.FirstOrDefault().ID select b;
                            var pret = from p in dbs.Price where resultProduct.FirstOrDefault<DB.Product>().ID == p.product_id orderby p.timestamp descending select p;
                            if (resultAlarm.Count() == 0)
                            {
                                dbs.AddToSubscribe(new DB.Subscribe() { user_id = UserID, product_id = ProductID, price = pret.First<DB.Price>().price1 == null ? 0 : (double)pret.First<DB.Price>().price1, percent = (Percent != -1 ? Percent : (double?)null) });
                                dbs.SaveChanges();
                                return new Mesaje() { Success = true, Mesaj = "Alarma a fost adaugata cu succes" };
                            }
                            else
                            {
                                var alarm = resultAlarm.First<DB.Subscribe>(); alarm.percent = (Percent != -1 ? Percent : (double?)null); alarm.price = pret.First<DB.Price>().price1 == null ? 0 : (double)pret.First<DB.Price>().price1;
                                dbs.SaveChanges();
                                return new Mesaje() { Success = true, Mesaj = "Alarma a fost modificata cu succes" };
                            }
                        }
                        else return new Mesaje() { Success = false, Mesaj = "Produsul nu (mai) exista in baza noastra de date" };
                    }
                    else
                    {
                        MonitorHackers();
                        return new Mesaje() { Success = false, Mesaj = "Va rugam delogati-va si logati-va inca odata" };
                    }
                }
                catch
                { return new Mesaje() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul adaugarii. Va rugam mai incercati odata" }; }
            }
        }
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public Mesaje RemoveUserAlarm(int UserID, string UserUsername, string Password, long ProductID)
        {
            if (UserIpuriBanate() >= 20) return new Mesaje() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var resultUser = (from u in dbs.Useri where u.ID == UserID && u.Username.Contains(UserUsername) && u.Username.Length == UserUsername.Length && u.Parola.StartsWith(Password) && u.Parola.Length == Password.Length select u.ID);
                    if (resultUser.Count() == 1)
                    {
                        var resultProduct = (from p in dbs.Product where p.ID == ProductID select p);
                        if (resultProduct.Count<DB.Product>() == 1)
                        {
                            var resultAlarm = from b in dbs.Subscribe where b.user_id == resultUser.FirstOrDefault() && b.product_id == resultProduct.FirstOrDefault().ID select b;
                            if (resultAlarm.Count() == 0)
                            {
                                return new Mesaje() { Success = false, Mesaj = "Alarma nu (mai) exista in baza noastra de date" };
                            }
                            else
                            {
                                dbs.Subscribe.DeleteObject(resultAlarm.FirstOrDefault<DB.Subscribe>());
                                dbs.SaveChanges();
                                return new Mesaje() { Success = true, Mesaj = "Alarma a fost stearsa" };
                            }
                        }
                        else return new Mesaje() { Success = false, Mesaj = "Produsul nu (mai) exista in baza noastra de date" };
                    }
                    else
                    {
                        MonitorHackers();
                        return new Mesaje() { Success = false, Mesaj = "Va rugam delogati-va si logati-va inca odata" };
                    }
                }
                catch
                { return new Mesaje() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul stergerii. Va rugam mai incercati odata" }; }
            }
        }
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public Mesaje GetUserAlarm(int UserID, string UserUsername, string Password, long ProductID)
        {
            if (UserIpuriBanate() >= 20) return new Mesaje() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var resultUser = (from u in dbs.Useri where u.ID == UserID && u.Username.Contains(UserUsername) && u.Username.Length == UserUsername.Length && u.Parola.StartsWith(Password) && u.Parola.Length == Password.Length select u.ID).Count();
                    if (resultUser == 1)
                    {
                        var resultProduct = (from p in dbs.Product where p.ID == ProductID select p.ID).Count();
                        if (resultProduct == 1)
                        {
                            var resultAlarm = (from b in dbs.Subscribe where b.product_id == ProductID && b.user_id == UserID select b.ID);

                            return new Mesaje() { Success = resultAlarm.Count() >= 1, Mesaj = "Bookmark " + (resultAlarm.Count() < 1 ? "in" : "") + "existent" };
                        }
                        else return new Mesaje() { Success = false, Mesaj = "Produsul nu (mai) exista in baza noastra de date" };
                    }
                    else
                    {
                        MonitorHackers();
                        return new Mesaje() { Success = false, Mesaj = "Va rugam delogati-va si logati-va inca odata" };
                    }
                }
                catch
                { return new Mesaje() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata" }; }

            }
        }
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public MesajeProduse GetUserAlarms(int UserID, string UserUsername, string Password, int Pagina, int IntrariPePagina)
        {
            if (UserIpuriBanate() >= 20) return new MesajeProduse() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var resultUser = (from u in dbs.Useri where u.ID == UserID && u.Username.Contains(UserUsername) && u.Username.Length == UserUsername.Length && u.Parola.StartsWith(Password) && u.Parola.Length == Password.Length select u.ID).Count();
                    if (resultUser == 1)
                    {
                        var produse = (from b in dbs.Subscribe where b.user_id == UserID join p in dbs.Product on b.product_id equals p.ID orderby b.Product.name ascending select new TipProdus() { ID = p.ID, name = p.name, brand = p.brand, description = p.description, imageSwatch = p.imageSwatch, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, UPC = p.UPC, ISBN = p.ISBN, categ_id = p.categ_id, categ_name = p.Category.name, authors = p.authors, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, KeyWords = p.KeyWords, Price = p.CurrPrice, NrAccesari = p.NrAccesari })
                            .Skip<TipProdus>(Pagina * IntrariPePagina).Take<TipProdus>(IntrariPePagina).ToList<TipProdus>();

                        foreach (var p in produse)
                        {
                            var rating = from r in dbs.Rating where r.product_id == p.ID select r.value; p.Rating = rating.Count() > 0 ? (rating.Sum() * 1.0 / rating.Count()) : 0;

                            //FOARTE IMPORTANT, nu am voie sa trimit in xml caractere precum < sau > sau </b> etc....
                            if (p.description != null) p.description = Microsoft.Security.Application.Encoder.HtmlEncode(p.description);
                            else p.description = String.Empty;
                            if (p.authors != null) p.authors = Microsoft.Security.Application.Encoder.HtmlEncode(p.authors).Replace("&#14;", " and ");
                            else p.authors = String.Empty;
                            p.linkSite = String.Concat("http://cotrobaie.cjb.net//product.aspx?ProductID=", p.ID.ToString());
                        }
                        return new MesajeProduse() { Success = true, Mesaj = produse.Count().ToString() + " alarme", Produse = produse };
                    }
                    else
                    {
                        MonitorHackers(); 
                        return new MesajeProduse() { Success = false, Mesaj = "Va rugam delogati-va si logati-va inca odata", Produse = new List<TipProdus>() };
                    }
                }
                catch
                { return new MesajeProduse() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata", Produse = new List<TipProdus>() }; }

            }
        }
        [ScriptMethod(UseHttpGet = true, XmlSerializeString = true, ResponseFormat = ResponseFormat.Xml)][WebMethod]
        public MesajeAlarme GetUserPriceAlarm(int UserID, string UserUsername, string Password, long ProductID)
        {
            if (UserIpuriBanate() >= 20) return new MesajeAlarme() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var resultUser = (from u in dbs.Useri where u.ID == UserID && u.Username.Contains(UserUsername) && u.Username.Length == UserUsername.Length && u.Parola.StartsWith(Password) && u.Parola.Length == Password.Length select u.ID).Count();
                    if (resultUser == 1)
                    {
                        var resultProduct = (from p in dbs.Product where p.ID == ProductID select p.ID).Count();
                        if (resultProduct == 1)
                        {
                            var resultAlarm = (from b in dbs.Subscribe where b.product_id == ProductID && b.user_id == UserID select new TipAlarma() { ID = b.ID, AlertPrice = b.alertPrice, AlertProcent = b.percent, PretVechi = b.price, product_id = b.product_id, user_id = b.user_id });

                            return new MesajeAlarme() { Success = resultAlarm.Count<TipAlarma>() >= 1, Mesaj = "Bookmark " + (resultAlarm.Count<TipAlarma>() < 1 ? "in" : "") + "existent", Alarme = resultAlarm.ToList<TipAlarma>() };
                        }
                        else return new MesajeAlarme() { Success = false, Mesaj = "Produsul nu (mai) exista in baza noastra de date", Alarme = new List<TipAlarma>() };
                    }
                    else
                    {
                        MonitorHackers();
                        return new MesajeAlarme() { Success = false, Mesaj = "Va rugam delogati-va si logati-va inca odata", Alarme = new List<TipAlarma>() };
                    }
                }
                catch
                { return new MesajeAlarme() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata", Alarme = new List<TipAlarma>() }; }

            }
        }

        #endregion

        #region Comments
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public Mesaje AddComment(int UserID, string UserUsername, string Password, long ProductID, string comment, string title)
        {
            if (UserIpuriBanate() >= 20) return new Mesaje() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var resultUser = (from u in dbs.Useri where u.ID == UserID && u.Username.Contains(UserUsername) && u.Username.Length == UserUsername.Length && u.Parola.StartsWith(Password) && u.Parola.Length == Password.Length select u.ID);
                    if (resultUser.Count() == 1)
                    {
                        var resultProduct = (from p in dbs.Product where p.ID == ProductID select p);
                        if (resultProduct.Count<DB.Product>() == 1)
                        {
                            var resultComment = from b in dbs.Comments where b.user_id == resultUser.FirstOrDefault() && b.product_id == resultProduct.FirstOrDefault().ID select b;
                                dbs.AddToComments(new DB.Comments() { user_id = UserID, product_id = ProductID, comment = comment, data = DateTime.Now, title=title });
                                dbs.SaveChanges();
                                return new Mesaje() { Success = true, Mesaj = "Comment adaugat cu succes" };
                        }
                        else return new Mesaje() { Success = false, Mesaj = "Produsul nu (mai) exista in baza noastra de date" };
                    }
                    else
                    {
                        MonitorHackers();
                        return new Mesaje() { Success = false, Mesaj = "Va rugam delogati-va si logati-va inca odata" };
                    }
                }
                catch
                { return new Mesaje() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul adaugarii. Va rugam mai incercati odata" }; }
            }
        }
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public Mesaje RemoveUserComment(int UserID, string UserUsername, string Password, int CommentID)
        {
            if (UserIpuriBanate() >= 20) return new Mesaje() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var resultUser = (from u in dbs.Useri where u.ID == UserID && u.Username.Contains(UserUsername) && u.Username.Length == UserUsername.Length && u.Parola.StartsWith(Password) && u.Parola.Length == Password.Length select u.ID);
                    if (resultUser.Count() == 1)
                    {
                        var resultComment = (from p in dbs.Comments where p.ID == CommentID select p);
                        if (resultComment.Count<DB.Comments>() == 1)
                        {

                            dbs.Comments.DeleteObject(resultComment.FirstOrDefault<DB.Comments>());
                            dbs.SaveChanges();
                            return new Mesaje() { Success = true, Mesaj = "Comment-ul a fost sters" };
                        }
                        else return new Mesaje() { Success = false, Mesaj = "Comentariul nu (mai) exista in baza noastra de date" };
                    }
                    else
                    {
                        MonitorHackers();
                        return new Mesaje() { Success = false, Mesaj = "Va rugam delogati-va si logati-va inca odata" };
                    }
                }
                catch
                { return new Mesaje() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul stergerii. Va rugam mai incercati odata" }; }
            }
        }
        [ScriptMethod(UseHttpGet = true, XmlSerializeString = true, ResponseFormat = ResponseFormat.Xml)]
        [WebMethod]
        public Mesaje EditUserComment(int UserID, string UserUsername, string Password, int CommentID, string comment, string title)
        {
            if (UserIpuriBanate() >= 20) return new Mesaje() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var resultUser = (from u in dbs.Useri where u.ID == UserID && u.Username.Contains(UserUsername) && u.Username.Length == UserUsername.Length && u.Parola.StartsWith(Password) && u.Parola.Length == Password.Length select u.ID);
                    if (resultUser.Count() == 1)
                    {
                        var resultComment = (from p in dbs.Comments where p.ID == CommentID select p);
                        if (resultComment.Count<DB.Comments>() == 1)
                        {
                            var r = resultComment.First();
                            r.comment = comment;
                            r.title = title;
                            
                            dbs.SaveChanges();
                            return new Mesaje() { Success = true, Mesaj = "Comment-ul a fost edidat" };
                        }
                        else return new Mesaje() { Success = false, Mesaj = "Comentariul nu (mai) exista in baza noastra de date" };
                    }
                    else
                    {
                        MonitorHackers();
                        return new Mesaje() { Success = false, Mesaj = "Va rugam delogati-va si logati-va inca odata" };
                    }
                }
                catch
                { return new Mesaje() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul stergerii. Va rugam mai incercati odata" }; }
            }
        }
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public MesajeComments GetUserComment(int UserID, string UserUsername, string Password, int CommentID)
        {
            if (UserIpuriBanate() >= 20) return new MesajeComments() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var resultUser = (from u in dbs.Useri where u.ID == UserID && u.Username.Contains(UserUsername) && u.Username.Length == UserUsername.Length && u.Parola.StartsWith(Password) && u.Parola.Length == Password.Length select u.ID).Count();
                    if (resultUser == 1)
                    {
                        var resultComment = (from p in dbs.Comments where p.ID == CommentID select p);
                        if (resultComment.Count() == 1)
                        {
                            var comment = resultComment.First<DB.Comments>();
                            var comm = new List<TipComment>();
                            comm.Add(new TipComment() { ID = comment.ID, user_id = comment.user_id, user_name = UserUsername, product_id = comment.product_id, product_name = comment.Product.name, comment = comment.comment, data = comment.data, titlu = comment.title });

                            return new MesajeComments() { Success = resultComment.Count() >= 1, Mesaj = "Comment " + (resultComment.Count() < 1 ? "in" : "") + "existent", Commenturi = comm };
                        }
                        else return new MesajeComments() { Success = false, Mesaj = "Commentariul nu (mai) exista in baza noastra de date", Commenturi = new List<TipComment>() };
                    }
                    else
                    {
                        MonitorHackers();
                        return new MesajeComments() { Success = false, Mesaj = "Va rugam delogati-va si logati-va inca odata", Commenturi = new List<TipComment>() };
                    }
                }
                catch
                { return new MesajeComments() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata", Commenturi = new List<TipComment>() }; }

            }
        }
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public MesajeComments GetUserComments(int UserID, string UserUsername, string Password, int Pagina, int IntrariPePagina)
        {
            if (UserIpuriBanate() >= 20) return new MesajeComments() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var resultUser = (from u in dbs.Useri where u.ID == UserID && u.Username.Contains(UserUsername) && u.Username.Length == UserUsername.Length && u.Parola.StartsWith(Password) && u.Parola.Length == Password.Length select u.ID).Count();
                    if (resultUser == 1)
                    {
                        var comments = (from c in dbs.Comments where c.user_id == UserID join p in dbs.Product on c.product_id equals p.ID orderby c.data descending select new TipComment() { ID = c.ID, comment = c.comment, data = c.data, user_id = UserID, user_name = c.Useri.Username, product_id = p.ID, product_name = p.name, titlu = c.title })
                            .Skip<TipComment>(Pagina * IntrariPePagina).Take<TipComment>(IntrariPePagina).ToList<TipComment>();

                        //FOARTE IMPORTANT, nu am voie sa trimit in xml caractere precum < sau > sau </b> etc....
                        foreach (var c in comments)
                        {
                            if (c != null) c.comment = Microsoft.Security.Application.Encoder.HtmlEncode(c.comment).Replace("&#14;", " and ");
                            else c.comment = String.Empty;
                        }
                        return new MesajeComments() { Success = true, Mesaj = comments.Count().ToString() + " commenturi", Commenturi = comments };
                    }
                    else
                    {
                        MonitorHackers();
                        return new MesajeComments() { Success = false, Mesaj = "Va rugam delogati-va si logati-va inca odata", Commenturi = new List<TipComment>() };
                    }
                }
                catch
                { return new MesajeComments() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata", Commenturi = new List<TipComment>() }; }

            }
        }
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public MesajeComments GetProductComments(long ProductID)
        {
            return GetProductComments2(ProductID, 0, 1000);
        }
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public MesajeComments GetProductComments2(long ProductID, int skip, int take)
        {
            if (UserIpuriBanate() >= 20) return new MesajeComments() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var resultProduct = (from u in dbs.Product where u.ID == ProductID select u.ID).Count();
                    if (resultProduct == 1)
                    {
                        var comments = (from c in dbs.Comments where c.product_id == ProductID orderby c.data descending select new TipComment() { ID = c.ID, comment = c.comment, data = c.data, user_id = c.Useri.ID, user_name = c.Useri.Username, product_id = ProductID, product_name = "", titlu=c.title })
                            .Skip<TipComment>(skip).Take<TipComment>(take).ToList<TipComment>();

                        //FOARTE IMPORTANT, nu am voie sa trimit in xml caractere precum < sau > sau </b> etc....
                        foreach (var c in comments)
                        {
                            if (c != null) c.comment = Microsoft.Security.Application.Encoder.HtmlEncode(c.comment).Replace("&#14;", " and ");
                            else c.comment = String.Empty;
                        }
                        return new MesajeComments() { Success = true, Mesaj = comments.Count().ToString() + " commenturi", Commenturi = comments };
                    }
                    else return new MesajeComments() { Success = false, Mesaj = "Produsul nu exista in baza noastra de date", Commenturi = new List<TipComment>() };
                }
                catch
                { return new MesajeComments() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata", Commenturi = new List<TipComment>() }; }

            }
        }
        #endregion

        #region Rating
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public Mesaje AddRating(int UserID, string UserUsername, string Password, long ProductID, int value)
        {
            if (UserIpuriBanate() >= 20) return new Mesaje() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var resultUser = (from u in dbs.Useri where u.ID == UserID && u.Username.Contains(UserUsername) && u.Username.Length == UserUsername.Length && u.Parola.StartsWith(Password) && u.Parola.Length == Password.Length select u.ID);
                    if (resultUser.Count() == 1)
                    {
                        var resultProduct = (from p in dbs.Product where p.ID == ProductID select p);
                        if (resultProduct.Count<DB.Product>() == 1)
                        {
                            var resultRating = from b in dbs.Rating where b.user_id == resultUser.FirstOrDefault() && b.product_id == resultProduct.FirstOrDefault().ID select b;
                            if (resultRating.Count() == 0)
                            {
                                dbs.AddToRating(new DB.Rating() { user_id = UserID, product_id = ProductID, value = value });
                                dbs.SaveChanges();
                                return new Mesaje() { Success = true, Mesaj = "Rating adaugat cu succes" };
                            }
                            else
                            {
                                var comm = resultRating.First<DB.Rating>(); comm.value = value;
                                dbs.SaveChanges();
                                return new Mesaje() { Success = true, Mesaj = "Rating modificat cu succes" };
                            }
                        }
                        else return new Mesaje() { Success = false, Mesaj = "Produsul nu (mai) exista in baza noastra de date" };
                    }
                    else
                    {
                        MonitorHackers();
                        return new Mesaje() { Success = false, Mesaj = "Va rugam delogati-va si logati-va inca odata" };
                    }
                }
                catch
                { return new Mesaje() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul adaugarii. Va rugam mai incercati odata" }; }
            }
        }
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public MesajeRatings GetUserRating(int UserID, string UserUsername, string Password, long ProductID)
        {
            if (UserIpuriBanate() >= 20) return new MesajeRatings() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var resultUser = (from u in dbs.Useri where u.ID == UserID && u.Username.Contains(UserUsername) && u.Username.Length == UserUsername.Length && u.Parola.StartsWith(Password) && u.Parola.Length == Password.Length select u.ID).Count();
                    if (resultUser == 1)
                    {
                        var resultProduct = (from p in dbs.Product where p.ID == ProductID select p.ID).Count();
                        if (resultProduct == 1)
                        {
                            var resultRating = (from b in dbs.Rating where b.product_id == ProductID && b.user_id == UserID select b);
                            double comm = 0;
                            if (resultRating.Count() > 0) { comm = resultRating.First<DB.Rating>().value; }

                            return new MesajeRatings() { Success = resultRating.Count() >= 1, Mesaj = "Rating " + (resultRating.Count() < 1 ? "in" : "") + "existent", rating = comm };
                        }
                        else return new MesajeRatings() { Success = false, Mesaj = "Produsul nu (mai) exista in baza noastra de date", rating = 0 };
                    }
                    else
                    {
                        MonitorHackers();
                        return new MesajeRatings() { Success = false, Mesaj = "Va rugam delogati-va si logati-va inca odata", rating = 0 };
                    }
                }
                catch
                { return new MesajeRatings() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata", rating = 0 }; }

            }
        }
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public MesajeRatings GetProductRating(long ProductID)
        {
            if (UserIpuriBanate() >= 20) return new MesajeRatings() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var resultProduct = (from u in dbs.Product where u.ID == ProductID select u.ID).Count();
                    if (resultProduct == 1)
                    {
                        var ratings = (from c in dbs.Rating where c.product_id == ProductID select c.value);
                        double ratings2 = ratings.Count() != 0 ? ratings.Sum() * 1.0 / ratings.Count() : 0;

                        //FOARTE IMPORTANT, nu am voie sa trimit in xml caractere precum < sau > sau </b> etc....
                        return new MesajeRatings() { Success = true, Mesaj = ratings.Count().ToString() + " ratinguri", rating  = ratings2 };
                    }
                    else return new MesajeRatings() { Success = false, Mesaj = "Produsul nu exista in baza noastra de date", rating=0 };
                }
                catch
                { return new MesajeRatings() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata", rating=0 }; }

            }
        }

        class Rating { public long ID { get; set; } public double Val { get; set; } }
        [ScriptMethod(UseHttpGet = true, XmlSerializeString = true, ResponseFormat = ResponseFormat.Xml)][WebMethod]
        public MesajeProduse GetTopRatings(int CountCateSaIaInConsiderare, int CoutRezultat)
        {
            if (UserIpuriBanate() >= 20) return new MesajeProduse() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    List<Rating>best=new List<Rating>();
                    var ratings = (from v in (from r in dbs.Rating group r by r.product_id into h select h) orderby v.Count() descending select v).Take(CountCateSaIaInConsiderare);
                    foreach (var r in ratings)
                        best.Add(new Rating() { ID = r.FirstOrDefault().product_id, Val = r.Sum(x => x.value) * 1.0 / r.Count() });
                    best = (from b in best orderby b.Val descending select b).Take(CoutRezultat).ToList();
                    
                    var ids=(from b in best select b.ID).ToList();
                    var result = (from p in dbs.Product where ids.Contains(p.ID) select new TipProdus() { ID = p.ID, name = p.name, categ_id = p.categ_id, categ_name = p.Category.name, brand = p.brand, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, ISBN = p.ISBN, UPC = p.UPC, Price = p.CurrPrice, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, authors = p.authors, NrAccesari = p.NrAccesari })
                               .ToList();

                    foreach (var p in result)
                    {
                        p.Rating = (from v in best where v.ID == p.ID select v.Val).FirstOrDefault();

                        p.description = String.Empty;
                        if (p.authors != null) p.authors = Microsoft.Security.Application.Encoder.HtmlEncode(p.authors).Replace("&#14;", " and ");
                        else p.authors = String.Empty;
                        p.linkSite = String.Concat("http://cotrobaie.cjb.net//product.aspx?ProductID=", p.ID.ToString());
                    }
                    return new MesajeProduse() { Success = true, Mesaj = "Cele mai bune " + result.Count().ToString() + " produse", Produse = result };
                }
                catch
                { return new MesajeProduse() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata", Produse=new List<TipProdus>() }; }
            }
        }
        [ScriptMethod(UseHttpGet = true, XmlSerializeString = true, ResponseFormat = ResponseFormat.Xml)][WebMethod]
        public MesajeProduse GetTopAccessed(int CoutRezultat)
        {
            if (UserIpuriBanate() >= 20) return new MesajeProduse() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var result = (from p in dbs.Product orderby p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, categ_id = p.categ_id, categ_name = p.Category.name, brand = p.brand, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, ISBN = p.ISBN, UPC = p.UPC, Price = p.CurrPrice, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, authors = p.authors, NrAccesari = p.NrAccesari })
                               .Take(CoutRezultat).ToList();

                    foreach (var p in result)
                    {
                        //p.Rating = (from v in best where v.ID == p.ID select v.Val).FirstOrDefault();

                        p.description = String.Empty;
                        if (p.authors != null) p.authors = Microsoft.Security.Application.Encoder.HtmlEncode(p.authors).Replace("&#14;", " and ");
                        else p.authors = String.Empty;
                        p.linkSite = String.Concat("http://cotrobaie.cjb.net//product.aspx?ProductID=", p.ID.ToString());
                    }
                    return new MesajeProduse() { Success = true, Mesaj = "Cele mai bune " + result.Count().ToString() + " produse", Produse = result };
                }
                catch
                { return new MesajeProduse() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata", Produse = new List<TipProdus>() }; }
            }
        }
        #endregion

        #region Produs
        #region GetProdusByKeywords
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public MesajeProduse GetProdusByKeywords1(string word)
        { return GetProdusByKeywords3(word); }
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public MesajeProduse GetProdusByKeywords2(string word, int pagina, int intrariPagina)
        { return GetProdusByKeywords3(word, pagina, intrariPagina); }

        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public MesajeProduse GetProdusByKeywords3(string word, int pagina = 0, int intrariPagina = 1000000, double PretMinim = 0, double PretMaxim = 1000000000, int category_id = -1, Ordonare ordonareTitlu = Ordonare.Crescator, Ordonare ordonarePret = Ordonare.Deloc, Ordonare ordonareAutor = Ordonare.Deloc, Ordonare ordonareBrand = Ordonare.Deloc, Ordonare ordonareCategorie = Ordonare.Deloc, byte NrOrdonari = 1)
        {
            if (UserIpuriBanate() >= 20) return new MesajeProduse() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    word = word.ToLower();
                    var word2 = " " + word;
                    string ordonari = ((ordonareTitlu != Ordonare.Crescator ? (ordonareTitlu == Ordonare.Descreascator ? "[name] DESC" : String.Empty) : "[name] ASC") + (NrOrdonari-- > 1 ? ", " : String.Empty)) +
                                    ((ordonareAutor != Ordonare.Crescator ? (ordonareAutor == Ordonare.Descreascator ? "[authors] DESC" : String.Empty) : "[authors] ASC") + (NrOrdonari-- > 1 ? ", " : String.Empty)) +
                                    ((ordonarePret != Ordonare.Crescator ? (ordonarePret == Ordonare.Descreascator ? "[CurrPrice] DESC" : String.Empty) : "[CurrPrice] ASC") + (NrOrdonari-- > 1 ? ", " : String.Empty)) +
                                    ((ordonareCategorie != Ordonare.Crescator ? (ordonareCategorie == Ordonare.Descreascator ? "[categ_id] DESC" : String.Empty) : "[categ_id] ASC") + (NrOrdonari-- > 1 ? ", " : String.Empty)) +
                                    ((ordonareBrand != Ordonare.Crescator ? (ordonareBrand == Ordonare.Descreascator ? "[brand] DESC" : String.Empty) : "[brand] ASC") + (NrOrdonari-- > 1 ? ", " : String.Empty));
                    ordonari = ordonari.Trim(new char[] { ' ', ',' });

                    List<TipProdus> produse = new List<TipProdus>();
                    if (ordonari.Contains("ASC"))
                        if (ordonari.Contains("name")) produse = (from p in dbs.Product where (p.KeyWords != null ? (p.KeyWords.StartsWith(word) || p.KeyWords.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.name ascending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari=p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("authors")) produse = (from p in dbs.Product where (p.KeyWords != null ? (p.KeyWords.StartsWith(word) || p.KeyWords.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.authors ascending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("CurrPrice")) produse = (from p in dbs.Product where (p.KeyWords != null ? (p.KeyWords.StartsWith(word) || p.KeyWords.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.CurrPrice ascending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("categ_id")) produse = (from p in dbs.Product where (p.KeyWords != null ? (p.KeyWords.StartsWith(word) || p.KeyWords.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.Category.name ascending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("brand")) produse = (from p in dbs.Product where (p.KeyWords != null ? (p.KeyWords.StartsWith(word) || p.KeyWords.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.brand ascending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else produse = (from p in dbs.Product where (p.KeyWords != null ? (p.KeyWords.StartsWith(word) || p.KeyWords.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                    else if (ordonari.Contains("DESC"))
                        if (ordonari.Contains("name")) produse = (from p in dbs.Product where (p.KeyWords != null ? (p.KeyWords.StartsWith(word) || p.KeyWords.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.name descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("authors")) produse = (from p in dbs.Product where (p.KeyWords != null ? (p.KeyWords.StartsWith(word) || p.KeyWords.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.authors descending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("CurrPrice")) produse = (from p in dbs.Product where (p.KeyWords != null ? (p.KeyWords.StartsWith(word) || p.KeyWords.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.CurrPrice descending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("categ_id")) produse = (from p in dbs.Product where (p.KeyWords != null ? (p.KeyWords.StartsWith(word) || p.KeyWords.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.Category.name descending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("brand")) produse = (from p in dbs.Product where (p.KeyWords != null ? (p.KeyWords.StartsWith(word) || p.KeyWords.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.brand descending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else produse = (from p in dbs.Product where (p.KeyWords != null ? (p.KeyWords.StartsWith(word) || p.KeyWords.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                    else produse = (from p in dbs.Product where (p.KeyWords != null ? (p.KeyWords.StartsWith(word) || p.KeyWords.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();

                    if (produse.Count<TipProdus>() == 0)
                        if (ordonari.Contains("ASC"))
                            if (ordonari.Contains("name")) produse = (from p in dbs.Product where p.name.StartsWith(word) || p.name.Contains(word2) || (p.authors != null ? (p.authors.StartsWith(word) || p.authors.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.name ascending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                            else if (ordonari.Contains("authors")) produse = (from p in dbs.Product where p.name.StartsWith(word) || p.name.Contains(word2) || (p.authors != null ? (p.authors.StartsWith(word) || p.authors.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.authors ascending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                            else if (ordonari.Contains("CurrPrice")) produse = (from p in dbs.Product where p.name.StartsWith(word) || p.name.Contains(word2) || (p.authors != null ? (p.authors.StartsWith(word) || p.authors.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.CurrPrice ascending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                            else if (ordonari.Contains("categ_id")) produse = (from p in dbs.Product where p.name.StartsWith(word) || p.name.Contains(word2) || (p.authors != null ? (p.authors.StartsWith(word) || p.authors.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.Category.name ascending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                            else if (ordonari.Contains("brand")) produse = (from p in dbs.Product where p.name.StartsWith(word) || p.name.Contains(word2) || (p.authors != null ? (p.authors.StartsWith(word) || p.authors.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.brand ascending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                            else produse = (from p in dbs.Product where p.name.StartsWith(word) || p.name.Contains(word2) || (p.authors != null ? (p.authors.StartsWith(word) || p.authors.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("DESC"))
                            if (ordonari.Contains("name")) produse = (from p in dbs.Product where p.name.StartsWith(word) || p.name.Contains(word2) || (p.authors != null ? (p.authors.StartsWith(word) || p.authors.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.name descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                            else if (ordonari.Contains("authors")) produse = (from p in dbs.Product where p.name.StartsWith(word) || p.name.Contains(word2) || (p.authors != null ? (p.authors.StartsWith(word) || p.authors.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.authors descending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                            else if (ordonari.Contains("CurrPrice")) produse = (from p in dbs.Product where p.name.StartsWith(word) || p.name.Contains(word2) || (p.authors != null ? (p.authors.StartsWith(word) || p.authors.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.CurrPrice descending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                            else if (ordonari.Contains("categ_id")) produse = (from p in dbs.Product where p.name.StartsWith(word) || p.name.Contains(word2) || (p.authors != null ? (p.authors.StartsWith(word) || p.authors.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.Category.name descending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                            else if (ordonari.Contains("brand")) produse = (from p in dbs.Product where p.name.StartsWith(word) || p.name.Contains(word2) || (p.authors != null ? (p.authors.StartsWith(word) || p.authors.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.brand descending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                            else produse = (from p in dbs.Product where p.name.StartsWith(word) || p.name.Contains(word2) || (p.authors != null ? (p.authors.StartsWith(word) || p.authors.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else produse = (from p in dbs.Product where p.name.StartsWith(word) || p.name.Contains(word2) || (p.authors != null ? (p.authors.StartsWith(word) || p.authors.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();

                    //if(ordonari.Contains("ASC"))produse= produse.OrderBy(x => ordonari.Contains("name") ? x.name : (ordonari.Contains("authors") ? x.authors : (ordonari.Contains("CurrPrice") ? String.Format("{0:00000.00}",x.Price) : (ordonari.Contains("categ_id") ? x.categ_name : (ordonari.Contains("brand") ? x.brand : x.KeyWords))))).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                    //else produse = produse.OrderByDescending(x => ordonari.Contains("name") ? x.name : (ordonari.Contains("authors") ? x.authors : (ordonari.Contains("CurrPrice") ? String.Format("{0:00000.00}", x.Price) : (ordonari.Contains("categ_id") ? x.categ_name : (ordonari.Contains("brand") ? x.brand : x.KeyWords))))).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                    
                    ThreadPool.QueueUserWorkItem(new WaitCallback(KeyWordNou), word);

                    foreach (var p in produse)
                    {
                        //dureaza prea mult....5 secunde pt 143 intrari
                        //try { var rating = from r in dbs.Rating where r.product_id == p.ID select r.value; p.Rating = rating.Count() > 0 ? (rating.Sum() * 1.0 / rating.Count()) : 0; }
                        //catch { }

                        //nici asta nu ne trebuie
                        //if (p.description!=null) p.description = Microsoft.Security.Application.Encoder.HtmlEncode(p.description);
                        p.description = String.Empty;
                        if (p.authors!=null) p.authors = Microsoft.Security.Application.Encoder.HtmlEncode(p.authors).Replace("&#14;", " and ");
                        else p.authors = String.Empty;
                        p.linkSite = String.Concat("http://cotrobaie.cjb.net//product.aspx?ProductID=", p.ID.ToString()); 
                    }
                    if(produse.Count<TipProdus>()==0)
                        return new MesajeProduse() { Success = false, Mesaj = "Cautarea a returnat 0 intrari in baza de date", Produse = new List<TipProdus>() };
                    else return new MesajeProduse() { Success = true, Mesaj = produse.Count().ToString() + " produse", Produse = produse };
                }
                catch
                { return new MesajeProduse() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata", Produse = new List<TipProdus>() }; }

            }
        }
        [ScriptMethod(UseHttpGet = true, XmlSerializeString = true, ResponseFormat = ResponseFormat.Xml)][WebMethod]
        public Mesaje GetProdusByKeywords3Count(string word,double PretMinim = 0, double PretMaxim = 1000000000, int category_id = -1)
        {
            if (UserIpuriBanate() >= 20) return new Mesaje() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    word = word.ToLower();
                    var word2 = " " + word;

                    var NrProduse = (from p in dbs.Product where (p.KeyWords != null ? (p.KeyWords.StartsWith(word) || p.KeyWords.Contains(word2)) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim select p.ID).Count();
                    return new Mesaje() { Success = false, Mesaj = NrProduse.ToString() + " produse" };
                }
                catch
                { return new Mesaje() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata" }; }
            }
        }
        [ScriptMethod(UseHttpGet = true, XmlSerializeString = true, ResponseFormat = ResponseFormat.Xml)][WebMethod]
        public MesajeProduse GetProdusByKeywords4(string [] words, int pagina = 0, int intrariPagina = 1000000, double PretMinim = 0, double PretMaxim = 1000000000, int category_id = -1, Ordonare ordonareTitlu = Ordonare.Crescator, Ordonare ordonarePret = Ordonare.Deloc, Ordonare ordonareAutor = Ordonare.Deloc, Ordonare ordonareBrand = Ordonare.Deloc, Ordonare ordonareCategorie = Ordonare.Deloc, byte NrOrdonari = 1)
        {
            if (UserIpuriBanate() >= 20) return new MesajeProduse() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    for(int i=0;i<words.Count();i++) words[i]=words[i].ToLower().Trim();
                    var words2 = words.Select(x=>" "+x).ToArray<string>();
                    string ordonari = ((ordonareTitlu != Ordonare.Crescator ? (ordonareTitlu == Ordonare.Descreascator ? "name DESC" : String.Empty) : "name ASC") + (NrOrdonari-- > 1 ? ", " : String.Empty)) +
                                    ((ordonareAutor != Ordonare.Crescator ? (ordonareAutor == Ordonare.Descreascator ? "authors DESC" : String.Empty) : "authors ASC") + (NrOrdonari-- > 1 ? ", " : String.Empty)) +
                                    ((ordonarePret != Ordonare.Crescator ? (ordonarePret == Ordonare.Descreascator ? "CurrPrice DESC" : String.Empty) : "CurrPrice ASC") + (NrOrdonari-- > 1 ? ", " : String.Empty)) +
                                    ((ordonareCategorie != Ordonare.Crescator ? (ordonareCategorie == Ordonare.Descreascator ? "categ_id DESC" : String.Empty) : "categ_id ASC") + (NrOrdonari-- > 1 ? ", " : String.Empty)) +
                                    ((ordonareBrand != Ordonare.Crescator ? (ordonareBrand == Ordonare.Descreascator ? "brand DESC" : String.Empty) : "brand ASC") + (NrOrdonari-- > 1 ? ", " : String.Empty));
                    ordonari = ordonari.Trim(new char[] { ' ', ',' });
                    
                    List<TipProdus> produse=new List<TipProdus>();
                    if (ordonari.Contains("ASC"))
                        if (ordonari.Contains("name")) produse = (from p in dbs.Product where (p.KeyWords != null ? (words.Where(x => p.KeyWords.StartsWith(x)).Count() > 0 || words2.Where(x => p.KeyWords.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.name ascending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("authors")) produse = (from p in dbs.Product where (p.KeyWords != null ? (words.Where(x => p.KeyWords.StartsWith(x)).Count() > 0 || words2.Where(x => p.KeyWords.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.authors ascending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("CurrPrice")) produse = (from p in dbs.Product where (p.KeyWords != null ? (words.Where(x => p.KeyWords.StartsWith(x)).Count() > 0 || words2.Where(x => p.KeyWords.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.CurrPrice ascending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("categ_id")) produse = (from p in dbs.Product where (p.KeyWords != null ? (words.Where(x => p.KeyWords.StartsWith(x)).Count() > 0 || words2.Where(x => p.KeyWords.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.Category.name ascending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("brand")) produse = (from p in dbs.Product where (p.KeyWords != null ? (words.Where(x => p.KeyWords.StartsWith(x)).Count() > 0 || words2.Where(x => p.KeyWords.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.brand ascending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else produse = (from p in dbs.Product where (p.KeyWords != null ? (words.Where(x => p.KeyWords.StartsWith(x)).Count() > 0 || words2.Where(x => p.KeyWords.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                    else if (ordonari.Contains("DESC"))
                        if (ordonari.Contains("name")) produse = (from p in dbs.Product where (p.KeyWords != null ? (words.Where(x => p.KeyWords.StartsWith(x)).Count() > 0 || words2.Where(x => p.KeyWords.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.name descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("authors")) produse = (from p in dbs.Product where (p.KeyWords != null ? (words.Where(x => p.KeyWords.StartsWith(x)).Count() > 0 || words2.Where(x => p.KeyWords.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.authors descending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("CurrPrice")) produse = (from p in dbs.Product where (p.KeyWords != null ? (words.Where(x => p.KeyWords.StartsWith(x)).Count() > 0 || words2.Where(x => p.KeyWords.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.CurrPrice descending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("categ_id")) produse = (from p in dbs.Product where (p.KeyWords != null ? (words.Where(x => p.KeyWords.StartsWith(x)).Count() > 0 || words2.Where(x => p.KeyWords.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.Category.name descending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("brand")) produse = (from p in dbs.Product where (p.KeyWords != null ? (words.Where(x => p.KeyWords.StartsWith(x)).Count() > 0 || words2.Where(x => p.KeyWords.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.brand descending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else produse = (from p in dbs.Product where (p.KeyWords != null ? (words.Where(x => p.KeyWords.StartsWith(x)).Count() > 0 || words2.Where(x => p.KeyWords.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                    else produse = (from p in dbs.Product where (p.KeyWords != null ? (words.Where(x => p.KeyWords.StartsWith(x)).Count() > 0 || words2.Where(x => p.KeyWords.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                    
                    if (produse.Count<TipProdus>() == 0)
                        if (ordonari.Contains("ASC"))
                            if (ordonari.Contains("name")) produse = (from p in dbs.Product where (words.Where(x => p.name.StartsWith(x)).Count() > 0 || words2.Where(x => p.name.StartsWith(x)).Count() > 0 || p.authors != null ? (words.Where(x => p.name.StartsWith(x)).Count() > 0 || words2.Where(x => p.name.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.name ascending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                            else if (ordonari.Contains("authors")) produse = (from p in dbs.Product where (words.Where(x => p.name.StartsWith(x)).Count() > 0 || words2.Where(x => p.name.StartsWith(x)).Count() > 0 || p.authors != null ? (words.Where(x => p.name.StartsWith(x)).Count() > 0 || words2.Where(x => p.name.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.authors ascending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                            else if (ordonari.Contains("CurrPrice")) produse = (from p in dbs.Product where (words.Where(x => p.name.StartsWith(x)).Count() > 0 || words2.Where(x => p.name.StartsWith(x)).Count() > 0 || p.authors != null ? (words.Where(x => p.name.StartsWith(x)).Count() > 0 || words2.Where(x => p.name.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.CurrPrice ascending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                            else if (ordonari.Contains("categ_id")) produse = (from p in dbs.Product where (words.Where(x => p.name.StartsWith(x)).Count() > 0 || words2.Where(x => p.name.StartsWith(x)).Count() > 0 || p.authors != null ? (words.Where(x => p.name.StartsWith(x)).Count() > 0 || words2.Where(x => p.name.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.Category.name ascending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                            else if (ordonari.Contains("brand")) produse = (from p in dbs.Product where (words.Where(x => p.name.StartsWith(x)).Count() > 0 || words2.Where(x => p.name.StartsWith(x)).Count() > 0 || p.authors != null ? (words.Where(x => p.name.StartsWith(x)).Count() > 0 || words2.Where(x => p.name.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.brand ascending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                            else produse = (from p in dbs.Product where (words.Where(x => p.name.StartsWith(x)).Count() > 0 || words2.Where(x => p.name.StartsWith(x)).Count() > 0 || p.authors != null ? (words.Where(x => p.name.StartsWith(x)).Count() > 0 || words2.Where(x => p.name.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                    if (ordonari.Contains("DESC"))
                        if (ordonari.Contains("name")) produse = (from p in dbs.Product where (words.Where(x => p.name.StartsWith(x)).Count() > 0 || words2.Where(x => p.name.StartsWith(x)).Count() > 0 || p.authors != null ? (words.Where(x => p.name.StartsWith(x)).Count() > 0 || words2.Where(x => p.name.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.name descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("authors")) produse = (from p in dbs.Product where (words.Where(x => p.name.StartsWith(x)).Count() > 0 || words2.Where(x => p.name.StartsWith(x)).Count() > 0 || p.authors != null ? (words.Where(x => p.name.StartsWith(x)).Count() > 0 || words2.Where(x => p.name.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.authors descending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("CurrPrice")) produse = (from p in dbs.Product where (words.Where(x => p.name.StartsWith(x)).Count() > 0 || words2.Where(x => p.name.StartsWith(x)).Count() > 0 || p.authors != null ? (words.Where(x => p.name.StartsWith(x)).Count() > 0 || words2.Where(x => p.name.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.CurrPrice descending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("categ_id")) produse = (from p in dbs.Product where (words.Where(x => p.name.StartsWith(x)).Count() > 0 || words2.Where(x => p.name.StartsWith(x)).Count() > 0 || p.authors != null ? (words.Where(x => p.name.StartsWith(x)).Count() > 0 || words2.Where(x => p.name.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.Category.name descending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("brand")) produse = (from p in dbs.Product where (words.Where(x => p.name.StartsWith(x)).Count() > 0 || words2.Where(x => p.name.StartsWith(x)).Count() > 0 || p.authors != null ? (words.Where(x => p.name.StartsWith(x)).Count() > 0 || words2.Where(x => p.name.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.brand descending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else produse = (from p in dbs.Product where (words.Where(x => p.name.StartsWith(x)).Count() > 0 || words2.Where(x => p.name.StartsWith(x)).Count() > 0 || p.authors != null ? (words.Where(x => p.name.StartsWith(x)).Count() > 0 || words2.Where(x => p.name.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                    else produse = (from p in dbs.Product where (words.Where(x => p.name.StartsWith(x)).Count() > 0 || words2.Where(x => p.name.StartsWith(x)).Count() > 0 || p.authors != null ? (words.Where(x => p.name.StartsWith(x)).Count() > 0 || words2.Where(x => p.name.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();

                    //if (ordonari.Contains("ASC")) produse = produse.OrderBy(x => ordonari.Contains("name") ? x.name : (ordonari.Contains("authors") ? x.authors : (ordonari.Contains("CurrPrice") ? String.Format("{0:00000.00}", x.Price) : (ordonari.Contains("categ_id") ? x.categ_name : (ordonari.Contains("brand") ? x.brand : x.KeyWords)))))
                    //else produse = produse.OrderByDescending(x => ordonari.Contains("name") ? x.name : (ordonari.Contains("authors") ? x.authors : (ordonari.Contains("CurrPrice") ? String.Format("{0:00000.00}", x.Price) : (ordonari.Contains("categ_id") ? x.categ_name : (ordonari.Contains("brand") ? x.brand : x.KeyWords))))).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();

                    foreach (var v in words)
                        ThreadPool.QueueUserWorkItem(new WaitCallback(KeyWordNou), v);

                    foreach (var p in produse)
                    {
                        //dureaza prea mult....5 secunde pt 143 intrari
                        //try { var rating = from r in dbs.Rating where r.product_id == p.ID select r.value; p.Rating = rating.Count() > 0 ? (rating.Sum() * 1.0 / rating.Count()) : 0; }
                        //catch { }

                        //nici asta nu ne trebuie
                        //if (p.description!=null) p.description = Microsoft.Security.Application.Encoder.HtmlEncode(p.description);
                        p.description = String.Empty;
                        if (p.authors != null) p.authors = Microsoft.Security.Application.Encoder.HtmlEncode(p.authors).Replace("&#14;", " and ");
                        else p.authors = String.Empty;
                        p.linkSite = String.Concat("http://cotrobaie.cjb.net//product.aspx?ProductID=", p.ID.ToString());
                    }
                    if (produse.Count<TipProdus>() == 0)
                        return new MesajeProduse() { Success = false, Mesaj = "Cautarea a returnat 0 intrari in baza de date", Produse = new List<TipProdus>() };
                    else return new MesajeProduse() { Success = true, Mesaj = produse.Count().ToString() + " produse", Produse = produse };
                }
                catch
                { return new MesajeProduse() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata", Produse = new List<TipProdus>() }; }

            }
        }
        [ScriptMethod(UseHttpGet = true, XmlSerializeString = true, ResponseFormat = ResponseFormat.Xml)][WebMethod]
        public Mesaje GetProdusByKeywords4Count(string []words, double PretMinim = 0, double PretMaxim = 1000000000, int category_id = -1)
        {
            if (UserIpuriBanate() >= 20) return new Mesaje() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    for (int i = 0; i < words.Count(); i++) words[i] = words[i].ToLower().Trim();
                    var words2 = words.Select(x => " " + x).ToArray<string>();

                    var NrProduse = (from p in dbs.Product where (p.KeyWords != null ? (words.Where(x => p.KeyWords.StartsWith(x)).Count() > 0 || words2.Where(x => p.KeyWords.StartsWith(x)).Count() > 0) : false) && (category_id != -1 ? p.categ_id == category_id : true) && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim select p.ID).Count();
                    return new Mesaje() { Success = false, Mesaj = NrProduse.ToString() + " produse" };
                }
                catch
                { return new Mesaje() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata" }; }
            }
        }
        #endregion

        #region GetUsersRecommendations
        [ScriptMethod(UseHttpGet = true, XmlSerializeString = true, ResponseFormat = ResponseFormat.Xml)][WebMethod]
        public MesajeProduse GetUsersRecommendations1(int UserID, string UserUsername, string Password)
        { return GetUsersRecommendations3(UserID, UserUsername, Password); }
        [ScriptMethod(UseHttpGet = true, XmlSerializeString = true, ResponseFormat = ResponseFormat.Xml)][WebMethod]
        public MesajeProduse GetUsersRecommendations2(int UserID, string UserUsername, string Password, int pagina, int intrariPagina)
        { return GetUsersRecommendations3(UserID, UserUsername, Password, pagina, intrariPagina); }
        [ScriptMethod(UseHttpGet = true, XmlSerializeString = true, ResponseFormat = ResponseFormat.Xml)][WebMethod]
        public MesajeProduse GetUsersRecommendations3(int UserID, string UserUsername, string Password, int pagina = 0, int intrariPagina = 1000000, double PretMinim = 0, double PretMaxim = 1000000000, int category_id = -1, Ordonare ordonareTitlu = Ordonare.Crescator, Ordonare ordonarePret = Ordonare.Deloc, Ordonare ordonareAutor = Ordonare.Deloc, Ordonare ordonareBrand = Ordonare.Deloc, Ordonare ordonareCategorie = Ordonare.Deloc, byte NrOrdonari = 1)
        {
            if (UserIpuriBanate() >= 20) return new MesajeProduse() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var resultUser = (from u in dbs.Useri where u.ID == UserID && u.Username.Contains(UserUsername) && u.Username.Length == UserUsername.Length && u.Parola.StartsWith(Password) && u.Parola.Length == Password.Length select u.ID);
                    if (resultUser.Count() == 1)
                    {
                        List<long> prod_ids = new List<long>();

                        var ratinguriUser = (from r in dbs.Rating where r.user_id == resultUser.FirstOrDefault() select r).ToList();

                        var ratinguriAltiUseri = (from r in dbs.Rating where r.user_id != UserID group r by r.user_id into h select h).ToList();

                        foreach (var rat in ratinguriAltiUseri)
                        {
                            var result = (from r in rat join r2 in ratinguriUser on r.product_id equals r2.product_id where r.value + 1 == r2.value || r.value - 1 == r2.value || r.value == r2.value select r.product_id).ToList();

                            if (result.Count() * 1.0*16/3 >= ratinguriUser.Count() || result.Count() * 1.0*16/3 >= rat.Count())//continuam, suntem pe cei 1/4 * 3/4 rat comune
                            {
                                var vvv = from v in rat where !prod_ids.Contains(v.product_id) && !result.Contains(v.product_id) && (v.value == 4 || v.value == 5) select v.product_id;
                                prod_ids.AddRange(vvv);
                            }

                        }
                        List<TipProdus> FinalList=new List<TipProdus>();
                        if(ordonareTitlu==Ordonare.Crescator)FinalList = (from pr in dbs.Product where prod_ids.Contains(pr.ID) && (category_id != -1 ? pr.categ_id == category_id : true) && pr.CurrPrice <= PretMaxim && pr.CurrPrice >= PretMinim orderby pr.name ascending select new TipProdus() { ID = pr.ID, authors = pr.authors, brand = pr.brand, categ_id = pr.categ_id, categ_name = pr.Category.name, imageLarge = pr.imageLarge, imageMedium = pr.imageMedium, imageSmall = pr.imageSmall, imageSwatch = pr.imageSwatch, ISBN = pr.ISBN, UPC = pr.UPC, Price = pr.CurrPrice, name = pr.name, linkAmazon = pr.linkAmazon, linkEbay = pr.linkEbay, NrAccesari=pr.NrAccesari }).ToList<TipProdus>();
                        else if (ordonareTitlu == Ordonare.Descreascator) FinalList = (from pr in dbs.Product where prod_ids.Contains(pr.ID) && (category_id != -1 ? pr.categ_id == category_id : true) && pr.CurrPrice <= PretMaxim && pr.CurrPrice >= PretMinim orderby pr.name descending select new TipProdus() { ID = pr.ID, authors = pr.authors, brand = pr.brand, categ_id = pr.categ_id, categ_name = pr.Category.name, imageLarge = pr.imageLarge, imageMedium = pr.imageMedium, imageSmall = pr.imageSmall, imageSwatch = pr.imageSwatch, ISBN = pr.ISBN, UPC = pr.UPC, Price = pr.CurrPrice, name = pr.name, linkAmazon = pr.linkAmazon, linkEbay = pr.linkEbay, NrAccesari = pr.NrAccesari }).ToList<TipProdus>();
                        else if (ordonareAutor == Ordonare.Crescator) FinalList = (from pr in dbs.Product where prod_ids.Contains(pr.ID) && (category_id != -1 ? pr.categ_id == category_id : true) && pr.CurrPrice <= PretMaxim && pr.CurrPrice >= PretMinim orderby pr.authors ascending, pr.NrAccesari descending select new TipProdus() { ID = pr.ID, authors = pr.authors, brand = pr.brand, categ_id = pr.categ_id, categ_name = pr.Category.name, imageLarge = pr.imageLarge, imageMedium = pr.imageMedium, imageSmall = pr.imageSmall, imageSwatch = pr.imageSwatch, ISBN = pr.ISBN, UPC = pr.UPC, Price = pr.CurrPrice, name = pr.name, linkAmazon = pr.linkAmazon, linkEbay = pr.linkEbay, NrAccesari = pr.NrAccesari }).ToList<TipProdus>();
                        else if (ordonareAutor == Ordonare.Descreascator) FinalList = (from pr in dbs.Product where prod_ids.Contains(pr.ID) && (category_id != -1 ? pr.categ_id == category_id : true) && pr.CurrPrice <= PretMaxim && pr.CurrPrice >= PretMinim orderby pr.authors descending, pr.NrAccesari descending select new TipProdus() { ID = pr.ID, authors = pr.authors, brand = pr.brand, categ_id = pr.categ_id, categ_name = pr.Category.name, imageLarge = pr.imageLarge, imageMedium = pr.imageMedium, imageSmall = pr.imageSmall, imageSwatch = pr.imageSwatch, ISBN = pr.ISBN, UPC = pr.UPC, Price = pr.CurrPrice, name = pr.name, linkAmazon = pr.linkAmazon, linkEbay = pr.linkEbay, NrAccesari = pr.NrAccesari }).ToList<TipProdus>();
                        else if (ordonarePret == Ordonare.Crescator) FinalList = (from pr in dbs.Product where prod_ids.Contains(pr.ID) && (category_id != -1 ? pr.categ_id == category_id : true) && pr.CurrPrice <= PretMaxim && pr.CurrPrice >= PretMinim orderby pr.CurrPrice ascending, pr.NrAccesari descending select new TipProdus() { ID = pr.ID, authors = pr.authors, brand = pr.brand, categ_id = pr.categ_id, categ_name = pr.Category.name, imageLarge = pr.imageLarge, imageMedium = pr.imageMedium, imageSmall = pr.imageSmall, imageSwatch = pr.imageSwatch, ISBN = pr.ISBN, UPC = pr.UPC, Price = pr.CurrPrice, name = pr.name, linkAmazon = pr.linkAmazon, linkEbay = pr.linkEbay, NrAccesari = pr.NrAccesari }).ToList<TipProdus>();
                        else if (ordonarePret == Ordonare.Descreascator) FinalList = (from pr in dbs.Product where prod_ids.Contains(pr.ID) && (category_id != -1 ? pr.categ_id == category_id : true) && pr.CurrPrice <= PretMaxim && pr.CurrPrice >= PretMinim orderby pr.CurrPrice descending, pr.NrAccesari descending select new TipProdus() { ID = pr.ID, authors = pr.authors, brand = pr.brand, categ_id = pr.categ_id, categ_name = pr.Category.name, imageLarge = pr.imageLarge, imageMedium = pr.imageMedium, imageSmall = pr.imageSmall, imageSwatch = pr.imageSwatch, ISBN = pr.ISBN, UPC = pr.UPC, Price = pr.CurrPrice, name = pr.name, linkAmazon = pr.linkAmazon, linkEbay = pr.linkEbay, NrAccesari = pr.NrAccesari }).ToList<TipProdus>();
                        else if (ordonareCategorie == Ordonare.Crescator) FinalList = (from pr in dbs.Product where prod_ids.Contains(pr.ID) && (category_id != -1 ? pr.categ_id == category_id : true) && pr.CurrPrice <= PretMaxim && pr.CurrPrice >= PretMinim orderby pr.categ_id ascending, pr.NrAccesari descending select new TipProdus() { ID = pr.ID, authors = pr.authors, brand = pr.brand, categ_id = pr.categ_id, categ_name = pr.Category.name, imageLarge = pr.imageLarge, imageMedium = pr.imageMedium, imageSmall = pr.imageSmall, imageSwatch = pr.imageSwatch, ISBN = pr.ISBN, UPC = pr.UPC, Price = pr.CurrPrice, name = pr.name, linkAmazon = pr.linkAmazon, linkEbay = pr.linkEbay, NrAccesari = pr.NrAccesari }).ToList<TipProdus>();
                        else if (ordonareCategorie == Ordonare.Descreascator) FinalList = (from pr in dbs.Product where prod_ids.Contains(pr.ID) && (category_id != -1 ? pr.categ_id == category_id : true) && pr.CurrPrice <= PretMaxim && pr.CurrPrice >= PretMinim orderby pr.categ_id descending, pr.NrAccesari descending select new TipProdus() { ID = pr.ID, authors = pr.authors, brand = pr.brand, categ_id = pr.categ_id, categ_name = pr.Category.name, imageLarge = pr.imageLarge, imageMedium = pr.imageMedium, imageSmall = pr.imageSmall, imageSwatch = pr.imageSwatch, ISBN = pr.ISBN, UPC = pr.UPC, Price = pr.CurrPrice, name = pr.name, linkAmazon = pr.linkAmazon, linkEbay = pr.linkEbay, NrAccesari = pr.NrAccesari }).ToList<TipProdus>();
                        else if (ordonareBrand == Ordonare.Crescator) FinalList = (from pr in dbs.Product where prod_ids.Contains(pr.ID) && (category_id != -1 ? pr.categ_id == category_id : true) && pr.CurrPrice <= PretMaxim && pr.CurrPrice >= PretMinim orderby pr.brand ascending, pr.NrAccesari descending select new TipProdus() { ID = pr.ID, authors = pr.authors, brand = pr.brand, categ_id = pr.categ_id, categ_name = pr.Category.name, imageLarge = pr.imageLarge, imageMedium = pr.imageMedium, imageSmall = pr.imageSmall, imageSwatch = pr.imageSwatch, ISBN = pr.ISBN, UPC = pr.UPC, Price = pr.CurrPrice, name = pr.name, linkAmazon = pr.linkAmazon, linkEbay = pr.linkEbay, NrAccesari = pr.NrAccesari }).ToList<TipProdus>();
                        else if (ordonareBrand == Ordonare.Descreascator) FinalList = (from pr in dbs.Product where prod_ids.Contains(pr.ID) && (category_id != -1 ? pr.categ_id == category_id : true) && pr.CurrPrice <= PretMaxim && pr.CurrPrice >= PretMinim orderby pr.brand descending, pr.NrAccesari descending select new TipProdus() { ID = pr.ID, authors = pr.authors, brand = pr.brand, categ_id = pr.categ_id, categ_name = pr.Category.name, imageLarge = pr.imageLarge, imageMedium = pr.imageMedium, imageSmall = pr.imageSmall, imageSwatch = pr.imageSwatch, ISBN = pr.ISBN, UPC = pr.UPC, Price = pr.CurrPrice, name = pr.name, linkAmazon = pr.linkAmazon, linkEbay = pr.linkEbay, NrAccesari = pr.NrAccesari }).ToList<TipProdus>();
                        else FinalList = (from pr in dbs.Product where prod_ids.Contains(pr.ID) && (category_id != -1 ? pr.categ_id == category_id : true) && pr.CurrPrice <= PretMaxim && pr.CurrPrice >= PretMinim orderby pr.NrAccesari descending select new TipProdus() { ID = pr.ID, authors = pr.authors, brand = pr.brand, categ_id = pr.categ_id, categ_name = pr.Category.name, imageLarge = pr.imageLarge, imageMedium = pr.imageMedium, imageSmall = pr.imageSmall, imageSwatch = pr.imageSwatch, ISBN = pr.ISBN, UPC = pr.UPC, Price = pr.CurrPrice, name = pr.name, linkAmazon = pr.linkAmazon, linkEbay = pr.linkEbay, NrAccesari = pr.NrAccesari }).ToList<TipProdus>();

                        foreach (var p in FinalList)
                        {
                            //dureaza prea mult....5 secunde pt 143 intrari
                            //try { var rating = from r in dbs.Rating where r.product_id == p.ID select r.value; p.Rating = rating.Count() > 0 ? (rating.Sum() * 1.0 / rating.Count()) : 0; }
                            //catch { }

                            //nici asta nu ne trebuie
                            //if (p.description!=null) p.description = Microsoft.Security.Application.Encoder.HtmlEncode(p.description);
                            p.description = String.Empty;
                            if (p.authors != null) p.authors = Microsoft.Security.Application.Encoder.HtmlEncode(p.authors).Replace("&#14;", " and ");
                            else p.authors = String.Empty;
                            p.linkSite = String.Concat("http://cotrobaie.cjb.net//product.aspx?ProductID=", p.ID.ToString());
                        }
                        return new MesajeProduse() { Success = true, Mesaj = "Recomandari generate cu succes", Produse = FinalList };
                    }
                    else
                    {
                        MonitorHackers();
                        return new MesajeProduse() { Success = false, Mesaj = "Va rugam delogati-va si logati-va inca odata", Produse = new List<TipProdus>() };
                    }
                }
                catch
                { return new MesajeProduse() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata", Produse = new List<TipProdus>() }; }
            }
        }
        [ScriptMethod(UseHttpGet = true, XmlSerializeString = true, ResponseFormat = ResponseFormat.Xml)][WebMethod]
        public Mesaje GetUsersRecommendations3Count(int UserID, string UserUsername, string Password, double PretMinim = 0, double PretMaxim = 1000000000, int category_id = -1)
        {
            if (UserIpuriBanate() >= 20) return new Mesaje() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var resultUser = (from u in dbs.Useri where u.ID == UserID && u.Username.Contains(UserUsername) && u.Username.Length == UserUsername.Length && u.Parola.StartsWith(Password) && u.Parola.Length == Password.Length select u.ID);
                    if (resultUser.Count() == 1)
                    {
                        List<long> prod_ids = new List<long>();

                        var ratinguriUser = (from r in dbs.Rating where r.user_id == resultUser.FirstOrDefault() select r).ToList();

                        var ratinguriAltiUseri = (from r in dbs.Rating where r.user_id != UserID group r by r.user_id into h select h).ToList();

                        foreach (var rat in ratinguriAltiUseri)
                        {
                            var result = (from r in rat join r2 in ratinguriUser on r.product_id equals r2.product_id where r.value + 1 == r2.value || r.value - 1 == r2.value || r.value == r2.value select r.product_id).ToList();

                            if (result.Count() * 1.0 * 16 / 3 >= ratinguriUser.Count() || result.Count() * 1.0 * 16 / 3 >= rat.Count())//continuam, suntem pe cei 1/4 * 3/4 rat comune
                            {
                                var vvv = from v in rat where !prod_ids.Contains(v.product_id) && !result.Contains(v.product_id) && (v.value == 4 || v.value == 5) select v.product_id;
                                prod_ids.AddRange(vvv);
                            }

                        }

                        return new Mesaje() { Success = true, Mesaj = prod_ids.Count().ToString()+ " recomandari" };
                    }
                    else
                    {
                        MonitorHackers();
                        return new Mesaje() { Success = false, Mesaj = "Va rugam delogati-va si logati-va inca odata" };
                    }
                }
                catch
                { return new Mesaje() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata" }; }
            }
        }
        #endregion

        #region GetProdusByID, Name, ISBN, UPC
        private bool UpdateAccesari(long ID)
        {
            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var prod = (from p in dbs.Product where p.ID == ID select p).First();
                    prod.NrAccesari = (short)(prod.NrAccesari != null ? (prod.NrAccesari + 1) : 1);
                    dbs.SaveChanges();
                }
                catch { return false; }
            }
            return true;
        }
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public MesajeProduse GetProdusByID(long ProdusID)
        {
            if (UserIpuriBanate() >= 20) return new MesajeProduse() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var prod = (from p in dbs.Product where p.ID == ProdusID select new TipProdus() { ID = p.ID, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, description = p.description, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, ISBN = p.ISBN, UPC = p.UPC, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, name = p.name, KeyWords = p.KeyWords, Price=p.CurrPrice, NrAccesari=p.NrAccesari }).ToList<TipProdus>();
                    foreach (var p in prod)
                    {
                        var rating = from r in dbs.Rating where r.product_id == p.ID select r.value; p.Rating = rating.Count() > 0 ? (rating.Sum() * 1.0 / rating.Count()) : 0;

                        if (p.description!=null) p.description = Microsoft.Security.Application.Encoder.HtmlEncode(p.description);
                        else p.description = String.Empty;
                        if (p.authors != null) p.authors = Microsoft.Security.Application.Encoder.HtmlEncode(p.authors).Replace("&#14;", " and ");
                        else p.authors = String.Empty;
                        p.linkSite = String.Concat("http://cotrobaie.cjb.net//product.aspx?ProductID=", p.ID.ToString());
                    }
                    if (prod.Count<TipProdus>() == 0)
                        return new MesajeProduse() { Success = false, Mesaj = "Produsul nu (mai) exista in baza noastra de date", Produse = new List<TipProdus>() };
                    else return new MesajeProduse() { Success = UpdateAccesari(ProdusID), Mesaj = "Produs existent", Produse = prod };
                }
                catch
                { return new MesajeProduse() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata", Produse = new List<TipProdus>() }; }
            }
        }
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public MesajeProduse GetProdusByName(string ProdusName)
        {
            if (UserIpuriBanate() >= 20) return new MesajeProduse() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var prod = (from p in dbs.Product where p.name.StartsWith(ProdusName) && p.name.Length == ProdusName.Length select new TipProdus() { ID = p.ID, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, description = p.description, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, ISBN = p.ISBN, UPC = p.UPC, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, name = p.name, KeyWords = p.KeyWords, Price = p.CurrPrice, NrAccesari = p.NrAccesari }).ToList<TipProdus>();
                    foreach (var p in prod)
                    {
                        var rating = from r in dbs.Rating where r.product_id == p.ID select r.value; p.Rating = rating.Count() > 0 ? (rating.Sum() * 1.0 / rating.Count()) : 0;

                        if (p.description != null) p.description = Microsoft.Security.Application.Encoder.HtmlEncode(p.description);
                        else p.description = String.Empty;
                        if (p.authors != null) p.authors = Microsoft.Security.Application.Encoder.HtmlEncode(p.authors).Replace("&#14;", " and ");
                        else p.authors = String.Empty;
                        p.linkSite = String.Concat("http://cotrobaie.cjb.net//product.aspx?ProductID=", p.ID.ToString());
                    }
                    if (prod.Count<TipProdus>() == 0)
                        return new MesajeProduse() { Success = false, Mesaj = "Produsul nu (mai) exista in baza noastra de date", Produse = new List<TipProdus>() };
                    else return new MesajeProduse() { Success = UpdateAccesari(prod.First().ID), Mesaj = "Produs existent", Produse = prod };
                }
                catch
                { return new MesajeProduse() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata", Produse = new List<TipProdus>() }; }
            }

        }
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public MesajeProduse GetProdusByISBN(string ProdusISBN)
        {
            if (UserIpuriBanate() >= 20) return new MesajeProduse() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var prod = (from p in dbs.Product where p.ISBN.Contains(ProdusISBN) && p.ISBN.Length == ProdusISBN.Length select new TipProdus() { ID = p.ID, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, description = p.description, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, ISBN = p.ISBN, UPC = p.UPC, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, name = p.name, KeyWords = p.KeyWords, Price = p.CurrPrice, NrAccesari = p.NrAccesari }).ToList<TipProdus>();
                    foreach (var p in prod)
                    {
                        var rating = from r in dbs.Rating where r.product_id == p.ID select r.value; p.Rating = rating.Count() > 0 ? (rating.Sum() * 1.0 / rating.Count()) : 0;

                        if (p.description != null) p.description = Microsoft.Security.Application.Encoder.HtmlEncode(p.description);
                        else p.description = String.Empty;
                        if (p.authors != null) p.authors = Microsoft.Security.Application.Encoder.HtmlEncode(p.authors).Replace("&#14;", " and ");
                        else p.authors = String.Empty;
                        p.linkSite = String.Concat("http://cotrobaie.cjb.net//product.aspx?ProductID=", p.ID.ToString());
                    }
                    if (prod.Count<TipProdus>() == 0)
                        return new MesajeProduse() { Success = false, Mesaj = "Produsul nu (mai) exista in baza noastra de date", Produse = new List<TipProdus>() };
                    else return new MesajeProduse() { Success = UpdateAccesari(prod.First().ID), Mesaj = "Produs existent", Produse = prod };
                }
                catch
                { return new MesajeProduse() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata", Produse = new List<TipProdus>() }; }
            }
        }
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public MesajeProduse GetProdusByUPC(string ProdusUPC)
        {
            if (UserIpuriBanate() >= 20) return new MesajeProduse() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var prod = (from p in dbs.Product where p.UPC.Contains(ProdusUPC) && p.UPC.Length == ProdusUPC.Length select new TipProdus() { ID = p.ID, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, description = p.description, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, ISBN = p.ISBN, UPC = p.UPC, linkAmazon = p.linkAmazon, linkEbay = p.linkEbay, name = p.name, KeyWords = p.KeyWords, Price = p.CurrPrice, NrAccesari = p.NrAccesari }).ToList<TipProdus>();
                    foreach (var p in prod)
                    {
                        var rating = from r in dbs.Rating where r.product_id == p.ID select r.value; p.Rating = rating.Count() > 0 ? (rating.Sum() * 1.0 / rating.Count()) : 0;

                        if (p.description != null) p.description = Microsoft.Security.Application.Encoder.HtmlEncode(p.description);
                        else p.description = String.Empty;
                        if (p.authors != null) p.authors = Microsoft.Security.Application.Encoder.HtmlEncode(p.authors).Replace("&#14;", " and ");
                        else p.authors = String.Empty;
                        p.linkSite = String.Concat("http://cotrobaie.cjb.net//product.aspx?ProductID=", p.ID.ToString());
                    }
                    if (prod.Count<TipProdus>() == 0)
                        return new MesajeProduse() { Success = false, Mesaj = "Produsul nu (mai) exista in baza noastra de date", Produse = new List<TipProdus>() };
                    else return new MesajeProduse() { Success = UpdateAccesari(prod.First().ID), Mesaj = "Produs existent", Produse = prod };
                }
                catch
                { return new MesajeProduse() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata", Produse = new List<TipProdus>() }; }
            }
        }
        #endregion

        #region GetProdusByCateg
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public MesajeProduse GetProdusByCategID1(int CategID)
        { return GetProdusByCategID3(CategID); }
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public MesajeProduse GetProdusByCategID2(int CategID, int pagina, int intrariPagina)
        { return GetProdusByCategID3(CategID, pagina, intrariPagina); }
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public MesajeProduse GetProdusByCategID3(int CategID, int pagina = 0, int intrariPagina = 1000000, double PretMinim = 0, double PretMaxim = 1000000000, Ordonare ordonareTitlu = Ordonare.Crescator, Ordonare ordonarePret = Ordonare.Deloc, Ordonare ordonareAutor = Ordonare.Deloc, Ordonare ordonareBrand = Ordonare.Deloc, byte NrOrdonari = 1)
        {
            if (UserIpuriBanate() >= 20) return new MesajeProduse() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    string ordonari = ((ordonareTitlu != Ordonare.Crescator ? (ordonareTitlu == Ordonare.Descreascator ? "name DESC" : String.Empty) : "name ASC") + (NrOrdonari-- > 1 ? ", " : String.Empty)) +
                                    ((ordonareAutor != Ordonare.Crescator ? (ordonareAutor == Ordonare.Descreascator ? "authors DESC" : String.Empty) : "authors ASC") + (NrOrdonari-- > 1 ? ", " : String.Empty)) +
                                    ((ordonarePret != Ordonare.Crescator ? (ordonarePret == Ordonare.Descreascator ? "CurrPrice DESC" : String.Empty) : "CurrPrice ASC") + (NrOrdonari-- > 1 ? ", " : String.Empty)) +
                                    ((ordonareBrand != Ordonare.Crescator ? (ordonareBrand == Ordonare.Descreascator ? "brand DESC" : String.Empty) : "brand ASC") + (NrOrdonari-- > 1 ? ", " : String.Empty));
                    ordonari = ordonari.Trim(new char[] { ' ', ',' });

                    List<TipProdus> produse=new List<TipProdus>();
                    if (ordonari.Contains("ASC"))
                        if (ordonari.Contains("name")) produse = (from p in dbs.Product where p.categ_id == CategID && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.name ascending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("authors")) produse = (from p in dbs.Product where p.categ_id == CategID && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.authors ascending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("CurrPrice")) produse = (from p in dbs.Product where p.categ_id == CategID && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.CurrPrice ascending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("categ_id")) produse = (from p in dbs.Product where p.categ_id == CategID && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.Category.name ascending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("brand")) produse = (from p in dbs.Product where p.categ_id == CategID && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.brand ascending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else produse = (from p in dbs.Product where p.categ_id == CategID && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                    else if (ordonari.Contains("DESC"))
                        if (ordonari.Contains("name")) produse = (from p in dbs.Product where p.categ_id == CategID && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.name descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("authors")) produse = (from p in dbs.Product where p.categ_id == CategID && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.authors descending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("CurrPrice")) produse = (from p in dbs.Product where p.categ_id == CategID && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.CurrPrice descending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("categ_id")) produse = (from p in dbs.Product where p.categ_id == CategID && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.Category.name descending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else if (ordonari.Contains("brand")) produse = (from p in dbs.Product where p.categ_id == CategID && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.brand descending, p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                        else produse = (from p in dbs.Product where p.categ_id == CategID && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();
                    else produse = (from p in dbs.Product where p.categ_id == CategID && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim orderby p.NrAccesari descending select new TipProdus() { ID = p.ID, name = p.name, authors = p.authors, brand = p.brand, categ_id = p.categ_id, categ_name = p.Category.name, ISBN = p.ISBN, UPC = p.UPC, imageLarge = p.imageLarge, imageMedium = p.imageMedium, imageSmall = p.imageSmall, imageSwatch = p.imageSwatch, Price = p.CurrPrice, Rating = 0, KeyWords = p.KeyWords, NrAccesari = p.NrAccesari }).Skip<TipProdus>(pagina * intrariPagina).Take<TipProdus>(intrariPagina).ToList<TipProdus>();

                    foreach (var p in produse)
                    {
                        //dureaza prea mult....5 secunde pt 143 intrari
                        //try { var rating = from r in dbs.Rating where r.product_id == p.ID select r.value; p.Rating = rating.Count() > 0 ? (rating.Sum() * 1.0 / rating.Count()) : 0; }
                        //catch { }

                        //nici asta nu ne trebuie
                        //if (p.description!=null) p.description = Microsoft.Security.Application.Encoder.HtmlEncode(p.description);
                        p.description = String.Empty;
                        if (p.authors != null) p.authors = Microsoft.Security.Application.Encoder.HtmlEncode(p.authors).Replace("&#14;", " and ");
                        else p.authors = String.Empty;
                        p.linkSite = String.Concat("http://cotrobaie.cjb.net//product.aspx?ProductID=", p.ID.ToString());
                    }
                    if (produse.Count<TipProdus>() == 0)
                        return new MesajeProduse() { Success = false, Mesaj = "Cautarea a returnat 0 intrari in baza de date", Produse = new List<TipProdus>() };
                    else return new MesajeProduse() { Success = true, Mesaj = produse.Count().ToString() + " produse", Produse = produse };
                }
                catch
                { return new MesajeProduse() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata", Produse = new List<TipProdus>() }; }

            }
        }
        [ScriptMethod(UseHttpGet = true, XmlSerializeString = true, ResponseFormat = ResponseFormat.Xml)][WebMethod]
        public Mesaje GetProdusByCategID3Count(int CategID, double PretMinim = 0, double PretMaxim = 1000000000)
        {
            if (UserIpuriBanate() >= 20) return new Mesaje() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var NrProduse = (from p in dbs.Product where p.categ_id == CategID && p.CurrPrice <= PretMaxim && p.CurrPrice >= PretMinim select p.ID).Count();
                    return new Mesaje() { Success = false, Mesaj = NrProduse.ToString() + " produse" };
                }
                catch
                { return new Mesaje() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata" }; }
            }
        }
        #endregion

        #region AddKeyWord
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public Mesaje AddKeyWord(string word)
        {
            if (UserIpuriBanate() >= 20) return new Mesaje() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            ThreadPool.QueueUserWorkItem(new WaitCallback(KeyWordNou), word);
            return new Mesaje() { Success = true, Mesaj = "KeyWordul se adauga Assync" };
        }
        #endregion
        #endregion

        #region Price
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public MesajePreturi GetProductPrice(long ProductID)
        {
            if (UserIpuriBanate() >= 20) return new MesajePreturi() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var pretui = (from p in dbs.Price where p.product_id == ProductID select new TipPreturi() { Data = p.timestamp, Pret = p.price1, SiteID = p.site_id, SiteName = p.Site.name }).ToList<TipPreturi>();
                    return new MesajePreturi() { Success = true, Mesaj = pretui.Count().ToString() + " preturi", Produse = pretui };
                }
                catch { return new MesajePreturi() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata", Produse = new List<TipPreturi>() }; }
            }
        }
        [ScriptMethod(UseHttpGet = true, XmlSerializeString = true, ResponseFormat = ResponseFormat.Xml)][WebMethod]
        public MesajePreturi GetProductPriceBest(long ProductID)
        {
            if (UserIpuriBanate() >= 20) return new MesajePreturi() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var rez = new List<TipPreturi>();
                    var pretui = (from p in dbs.Price where p.product_id == ProductID select new TipPreturi() { Data = p.timestamp, Pret = p.price1, SiteID = p.site_id, SiteName = p.Site.name }).ToList<TipPreturi>();
                    var Prices = from i in (from p in pretui select p) group i by i.SiteID into h select h;
                    foreach (var p in Prices)
                        rez.Add(p.OrderByDescending(x => x.Data).First());

                    return new MesajePreturi() { Success = true, Mesaj = pretui.Count().ToString() + " preturi", Produse = rez };
                }
                catch { return new MesajePreturi() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata", Produse = new List<TipPreturi>() }; }
            }
        }
        #endregion

        #region Categorii
        [ScriptMethod(UseHttpGet = true,XmlSerializeString=true, ResponseFormat=ResponseFormat.Xml)][WebMethod]
        public MesajeCategorii GetCategorii()
        {
            if (UserIpuriBanate() >= 20) return new MesajeCategorii() { Success = false, Mesaj = "Ai fost banat 48 de ore" };

            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    var categorii = Genereaza(dbs.Category.ToList<DB.Category>(), null);
                    return new MesajeCategorii() { Success = true, Mesaj = "Categorii generate cu succes", Categorii = categorii };
                }
                catch { return new MesajeCategorii() { Success = false, Mesaj = "Ne pare rau dar a aparut o eroare in momentul cautarii. Va rugam mai incercati odata", Categorii = new List<TipCategorii>() }; }
            }
        }
        private List<TipCategorii> Genereaza(List<DB.Category> categorii, int? id)
        {
            var rez = new List<TipCategorii>();
            foreach (var c in categorii.Where(x=>x.categ_id==id))
                rez.Add(new TipCategorii() { ID = c.ID, name = c.name, description = c.description, SubCategorii = Genereaza(c.Category1.ToList<DB.Category>(),c.ID) });
            return rez;
        }
        
        #endregion

        #region Adaug KeyWord nou pe Thread nou
        private static void KeyWordNou(object state)
        {
            Thread.Sleep(1000);
            string word = (string)state;
            var word2 = " " + word;
            using (var dbs = new DB.DBCotrobaie())
            {
                var va = from p in dbs.Product
                         where (p.name.StartsWith(word) || p.name.Contains(word2) || (p.authors != null ? (p.authors.StartsWith(word) || p.authors.Contains(word2)) : false)) && (p.KeyWords == null || (!p.KeyWords.StartsWith(word) && !p.KeyWords.Contains(word2)))
                         select p;
                if (va.Count() < 15) return;//produsul nu e chiar asa important:(
                foreach (var v in va)
                    if (v.KeyWords == null) v.KeyWords = word + "#";
                    else if(v.KeyWords.Length+word.Length<235) v.KeyWords += word + "#";
                dbs.SaveChanges();
            }
        }
        #endregion
    }
}

